简体   繁体   English

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

[英]How to access state inside of event function?

I have a react component that is using a calendar to handle some date picking stuff. 我有一个使用日历处理某些日期选择内容的react组件。 My jsx is pretty simple you can see it below: 我的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)
  }

This renders my calendar fine and the date string after Date: looks correct. 这样可以使我的日历正常显示,并且Date:之后的日期字符串看起来正确。 My problem is that this is always null when I change the date. 我的问题是,当我更改日期时, this始终为null。 I would like to be able to access this.state.date from the dateChange function but I can't figure out how to do this. 我想能够访问this.state.datedateChange功能,但我无法弄清楚如何做到这一点。 I attempted to bind using the code below: 我尝试使用以下代码进行绑定:

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

But this returns the error Cannot read property 'bind' of undefined . 但这将返回错误Cannot read property 'bind' of undefined

How do I make this and by extension my current state available in my dateChange function? 如何使它以及通过我的dateChange函数扩展我的当前状态?

Define it inside of your class, as a class method, without function word 在类内部将其定义为类方法,不带功能词

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);
    }
}

That way you can use this.dateChange = this.dateChange.bind(this) to bind this to your class 你可以用这种方式this.dateChange = this.dateChange.bind(this)绑定this对你的类

I also moved the state to your constructor; 我也将状态移到了您的构造函数中。 that's where it is normally initialized 那是通常初始化的地方

And I removed Date: {this.state.date.toString()} because I am not sure what were you trying to do wit it (is it another Component?) - anyway I do not think it affects the response to your question 我删除了Date: {this.state.date.toString()}因为我不确定您要尝试使用它(是否是另一个组件?)-无论如何,我认为它不会影响对您问题的回答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM