代码之家  ›  专栏  ›  技术社区  ›  MeltingDog

反应:如何从处理函数中读取状态?

  •  0
  • MeltingDog  · 技术社区  · 2 年前

    我是React的新手,在现有React组件上工作(该组件似乎是以旧样式构建的,没有挂钩)。

    我想在处理函数中读取并设置状态。我有以下代码:

    export default class MyComponent extends React.Component { 
    
    static defaultProps = {
        data: {}
    };
    
    constructor(props) {
         super(props);
    
         // Other states
    
         this.state.myState = false;
    };
    
    handleMyChange() {
        if (!this.state.myState) {
            console.log("hello world");
        }
    }
    

    然而我得到了错误 Cannot read properties of undefined .

    我试过各种各样的 state.myState 但我不确定我应该做什么。

    谁能给我指出正确的方向吗?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Ryan Le    2 年前

    为了拥有 this 在函数的上下文中,首先需要在构造函数中绑定它

    以下是官方文件中的一个小例子:

    import React from "react";
    
    export default class SayHello extends React.Component {
      constructor(props) {
        super(props);
        this.state = { message: "Hello!" };
        // This line is important!
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick() {
        alert(this.state.message);
      }
    
      render() {
        // Because `this.handleClick` is bound, we can use it as an event handler.
        return <button onClick={this.handleClick}>Say hello</button>;
      }
    }
    

    Edit withered-snow-z17lju