饮水思源:https://www.bilibili.com/video/BV1wy4y1D7JT?p=12

一句话:状态驱动页面,状态改变,页面改变。

简单组件

被传入的数据可在组件中通过 this.props 在 render() 访问。

  <script type="text/babel">
    let 容器 = document.querySelector("#test");
    class 这是一个简单组件 extends React.Component {
      render() {
        console.log(this) 
        return <h2>我是{this.props.name}</h2>
      }
    }
    ReactDOM.render(<这是一个简单组件 name={"火车王"} />, 容器);
  </script>

有状态组件

直接抄官网:除了使用外部数据(通过 this.props 访问)以外,组件还可以维护其内部的状态数据(通过 this.state 访问)。当组件的状态数据改变时,组件会再次调用 render() 方法重新渲染对应的标记。

解决类中this指向问题:https://www.bilibili.com/video/BV1wy4y1D7JT?p=16

效果演示(点击文字改变):

React笔记 #04# 对state的理解

状态不能直接更改,要借助内部API更改(严重注意!),且setState是合并不是替换。错误示例:

  <script type="text/babel">
    let 容器 = document.querySelector("#test");

    let that;
    class 这是一个有状态的组件 extends React.Component {
      constructor(props) {
        super(props) // 为了接属性
        this.state = {
          name: "火车王",
        }

        that = this;
      }

      render() {
        console.log(this) 
        return <h2 onClick={changeName}>我是{this.state.name}</h2>
      }
    }

    ReactDOM.render(<这是一个有状态的组件 />, 容器);

    function changeName() {
      console.log(that)
      console.log("函数被" + that.state.name + "触发");
      if (that.state.name == "火车王") {
        that.state.name = "火车王的儿子"
      } else {
        that.state.name = "火车王"
      }
    }
  </script>
无效代码

相关文章:

  • 2022-12-23
  • 2021-09-11
  • 2022-12-23
  • 2022-01-23
  • 2021-05-31
  • 2021-10-04
  • 2022-12-23
  • 2021-08-18
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案