全局引入React 和 ReactDOM

React是一个全局对象:

image.png

ReactDom也是一个全局对象:

image.png

用CDN的方式引入并用React创建一个对象:
image.png
React.createElement("div", { className: "red" }, [xxx])React链接

  1. //index.html
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>Parcel Sandbox</title>
  6. </head>
  7. <body>
  8. <div id="root"></div>
  9. <script src="https://cdn.bootcdn.net/ajax/libs/react/17.0.0/umd/react.development.js"></script>
  10. <script src="https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.0/umd/react-dom.development.js"></script>
  11. <script src="src/index.js"></script>
  12. </body>
  13. </html>
  14. //index.js
  15. let n = 0;
  16. console.log(n);
  17. const APP = () =>
  18. React.createElement("div", { className: "red" }, [
  19. n,
  20. window.React.createElement(
  21. "button",
  22. {
  23. onClick: () => {
  24. n += 1;
  25. window.ReactDOM.render(APP(), root);
  26. console.log(n);
  27. }
  28. },
  29. "+1"
  30. )
  31. ]);
  32. 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类组件

  1. //函数组件
  2. function Welcome(props){
  3. return <h1>Hello,{props.name}</h1>
  4. }
  5. <Welcome name="jack"/>
  6. //类组件
  7. class Welcome extends React.component {
  8. render(){
  9. return <h1>Hello,{this.props.name}</h1>
  10. }
  11. }
  12. <Welcome name="jack"/>

JSX

  1. //jsx
  2. 函数/变量都要有{}包住
  3. <div id="app"></div>
  4. let n = 0;
  5. const App = () => (
  6. <div>
  7. {n}
  8. <button
  9. onClick={() => {
  10. n += 2;
  11. render();
  12. }}
  13. >
  14. +2
  15. </button>
  16. </div>
  17. );
  18. const render = () =>
  19. ReactDOM.render(<App />, document.querySelector("#app"));
  20. render();

State:类组件

State,SetState不会改变原来的对象,而是生成一个新的对象去赋值(数据不可变)

  1. class Son extends React.Component {
  2. constructor() {
  3. super();
  4. this.state = {
  5. n: 0
  6. };
  7. }
  8. add() { //异步更新
  9. //this.setState({ n: this.state.n + 1 });
  10. this.setState((state)=>{
  11. const x = state.n + 1
  12. console.log(x)
  13. })
  14. }
  15. render() {
  16. return (
  17. <div className="Son">
  18. n: {this.state.n}
  19. //事件绑定
  20. <button onClick={() => this.add()}>+1</button>
  21. <Grandson />
  22. </div>
  23. );
  24. }
  25. }

类组件里事件:

  1. class x extends React.component{
  2. constructor{
  3. this.add = () => this.setState({n:this.state.n + 1})
  4. }
  5. }
  6. //
  7. class x extends React.component{
  8. add = () => this.setState({n:this.state.n + 1})
  9. }

箭头函数的this是当前对象的,而普通函数的this是在window上