代码之家  ›  专栏  ›  技术社区  ›  Abe Miessler

如何访问事件函数内部的状态?

  •  -1
  • Abe Miessler  · 技术社区  · 5 年前

    我有一个反应成分 using a calendar 处理一些约会的事情。我的jsx非常简单,您可以在下面看到:

      state = { 
        date: new Date(),
      };
    
      render() {
        return (
        //left out for the sake of brevity...
        Date: {this.state.date.toString()}
        <Calendar onChange={dateChange} activeStartDate={this.state.date} />
        //...
      )}
    
      function dateChange(date) {
        console.log(date)
        console.log(this)
      }
    

    这将使我的日历和日期字符串 Date: 看起来不错。我的问题是 this 当我更改日期时总是空的。我希望能够访问 this.state.date dateChange

      constructor() {
        super();
        this.dateChange = this.dateChange.bind(this)
      }
    

    但这会返回错误 Cannot read property 'bind' of undefined .

    我该如何使我的当前状态在我的 日期更改

    1 回复  |  直到 5 年前
        1
  •  1
  •   Gonzalo.-    5 年前

    在类中定义它,作为类方法,不使用虚词

    class yourClass extends React.Component {
        constructor(props) {
            super(props);
            this.state = { date: new Date() };
            this.dateChange = this.dateChange.bind(this);
          }
    
        render() {
            return (
            //left out for the sake of brevity...
            <Calendar onChange={this.dateChange} activeStartDate={this.state.date} />
            //...
            );
        }
    
        dateChange(date) {
            console.log(date);
            console.log(this);
        }
    }
    

    这样你就可以使用 this.dateChange = this.dateChange.bind(this) 捆绑 this

    我也把状态转移到你的构造器;这就是它通常初始化的地方

    Date: {this.state.date.toString()}