出现多次的要学会合并
eg.
function render() {
let button2 = React.createElement("button", { onClick: onClickButton2 }, "-");
let button = React.createElement("button", { onClick: onClickButton }, "+");
let span = React.createElement("span", { className: "red" }, number);
let div = React.createElement(
"div",
{ className: "parent" },
span,
button,
button2
);
ReactDOM.render(div, document.querySelector("#root"));
}
其中
let button2 = React.createElement("button", { onClick: onClickButton2 }, "-");
let button = React.createElement("button", { onClick: onClickButton }, "+");
let span = React.createElement("span", { className: "red" }, number);
let div = React.createElement(
"div",
{ className: "parent" },
span,
button,
button2
);
createment出现多次,可以省一点的写
function render() {
let h = React.createElement;
let button2 = h("button", { onClick: onClickButton2 }, "-");
let button = h("button", { onClick: onClickButton }, "+");
let span = h("span", { className: "red" }, number);
let div = h("div", { className: "parent" }, span, button, button2);
ReactDOM.render(div, document.querySelector("#root"));
}
省略很多代码
减少变量
上面那行代码,我们声明了3个可以省略的变量只需要
function render() {
let h = React.createElement;
//react里面直接做虚拟的div到时候再投射到html中,第一个是表示何种元素,然后是属性,最后是内容
let div = h(
"div",
{ className: "parent" },
h("span", { className: "red" }, number),
h("button", { onClick: onClickButton }, "+"),
h("button", { onClick: onClickButton2 }, "-")
); //以上三行都是内容
ReactDOM.render(div, document.querySelector("#root"));
}
将那三行代码直接放进div的内容中,可少整几个变量
JSX
发现
let div = h(
"div",
{ className: "parent" },
h("span", { className: "red" }, number),
h("button", { onClick: onClickButton }, "+"),
h("button", { onClick: onClickButton2 }, "-")
)
格式与html中标签类似
<div class="parent">
<span class="red">{number}</span>
<button onClick={onClickButton}>+</button>
<button onClick={onClickButton}>-</button>//所有的变量要用{}括起来
</div>
都是先写标签元素,再写属性,再写内容,所以JS发明了一个程序叫做JSX,让我们可以按照下面html标签写法来写JS,然后它负责转译成上面那种正规语法,简而言之,我们可以用html的方法来写React
这个好东西叫做JSX,只要在babel上就能找到
网友评论