React18 组件化,this绑定问题

124 阅读1分钟

类组件写法

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script type="text/babel">
      class App extends React.Component {
        // 组件数据
        constructor() {
          super();
          this.state = {
            msg: "hello world!",
          };
          //   修改this 方法2
          //   对需要绑定的方法,提前绑定好this
          this.changeText = this.changeText.bind(this);
        }
        // 组件方法
        changeText() {
          console.log("=> ", this); //undefined   严格模式下,class里函数的this是undefined
          // 如果不改变this指向,会报错  Uncaught TypeError: Cannot read properties of undefined (reading 'setState')
          this.setState({
            msg: "hello react!",
          });
          //   setState() do what
          //   1.将state中msg值修改
          //   2.自动重新执行render函数
        }

        // 渲染内容 render方法
        render() {
          console.log("this=> ", this); //组件实例
          return (
            <div>
              <h2>{this.state.msg}</h2>
              <button onClick={this.changeText.bind(this)}>修改文本</button>
              <button onClick={this.changeText}>修改文本</button>
            </div>
          );
        }
      }
      // 渲染 React 组件
      const root = ReactDOM.createRoot(document.getElementById("root"));
      root.render(<App />);
    </script>
  </body>
</html>