React是一个全局对象:
ReactDom也是一个全局对象:
用CDN的方式引入并用React创建一个对象:
React.createElement("div", { className: "red" }, [xxx])
React链接
//index.html
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
</head>
<body>
<div id="root"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/react/17.0.0/umd/react.development.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.0/umd/react-dom.development.js"></script>
<script src="src/index.js"></script>
</body>
</html>
//index.js
let n = 0;
console.log(n);
const APP = () =>
React.createElement("div", { className: "red" }, [
n,
window.React.createElement(
"button",
{
onClick: () => {
n += 1;
window.ReactDOM.render(APP(), root);
console.log(n);
}
},
"+1"
)
]);
window.ReactDOM.render(APP(), root);
直接用等于号会立刻取值并记录下料,箭头函数会延迟执行,在每次调用时执行const APP1 = React.createElement("div", { className: "red" }, n)
APP1是一个React元素const APP2 = ()=> React.createElement("div", { className: "red" }, n)
APP2是一个React函数组件
函数组件vs类组件
//函数组件
function Welcome(props){
return <h1>Hello,{props.name}</h1>
}
<Welcome name="jack"/>
//类组件
class Welcome extends React.component {
render(){
return <h1>Hello,{this.props.name}</h1>
}
}
<Welcome name="jack"/>
JSX
//jsx
函数/变量都要有{}包住
<div id="app"></div>
let n = 0;
const App = () => (
<div>
{n}
<button
onClick={() => {
n += 2;
render();
}}
>
+2
</button>
</div>
);
const render = () =>
ReactDOM.render(<App />, document.querySelector("#app"));
render();
State:类组件
State,SetState不会改变原来的对象,而是生成一个新的对象去赋值(数据不可变)
class Son extends React.Component {
constructor() {
super();
this.state = {
n: 0
};
}
add() { //异步更新
//this.setState({ n: this.state.n + 1 });
this.setState((state)=>{
const x = state.n + 1
console.log(x)
})
}
render() {
return (
<div className="Son">
n: {this.state.n}
//事件绑定
<button onClick={() => this.add()}>+1</button>
<Grandson />
</div>
);
}
}
类组件里事件:
class x extends React.component{
constructor{
this.add = () => this.setState({n:this.state.n + 1})
}
}
//
class x extends React.component{
add = () => this.setState({n:this.state.n + 1})
}
箭头函数的this是当前对象的,而普通函数的this是在window上