簡體   English   中英

如何訪問事件函數內部的狀態?

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

我有一個使用日歷處理某些日期選擇內容的react組件。 我的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始終為null。 我想能夠訪問this.state.datedateChange功能,但我無法弄清楚如何做到這一點。 我嘗試使用以下代碼進行綁定:

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

但這將返回錯誤Cannot read property 'bind' of undefined

如何使它以及通過我的dateChange函數擴展我的當前狀態?

在類內部將其定義為類方法,不帶功能詞

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()}因為我不確定您要嘗試使用它(是否是另一個組件?)-無論如何,我認為它不會影響對您問題的回答

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM