首页 > 解决方案 > 以组件为数据的材料表未在 onChange 事件中传递组件上下文

问题描述

我尝试将组件作为数据添加到材料表中,但我无法访问组件的“this”上下文以更新 onChange 函数中的状态。材料表提供的可编辑功能不符合我的要求。

class ClubList extends Component {
  state = { clubs: '', tableClubs: [] };

  changeDate=(change)=>{      
    console.log(this) //returns undefined.  I need to update state here but not able to access 'this' context of component
  }


  addClub = (event, clubs) => {
    let enteredClubs = this.state.clubs;
    let allClubs = this.props.clubs;
    let tableClubs = [];
    let enteredClubsArray = enteredClubs.split(/[ ,]+/);
    for (let clubs in enteredClubsArray) {
      tableClubs.push(allClubs.find(({ number }) => number == enteredClubsArray[clubs]));
    }
    tableClubs.map(
      (clubs) => (
        (clubs.scheduledDate = (        
          <DateComponent name="eventDate"
value={this.props.createData.eventDate} 
handleChange={this.changeDate} /> //Im calling the function here
        )),
        (clubs.city = clubs.city)
      )
    );
    this.setState({ clubs: '', tableClubs });
    this.clubsForCreate(tableClubs);
  };

  render() {
    return (
      <div className="clubSection">
            <TextComponent
              label="Enter Clubs"
              name="clubs"
              variant="outlined"
              handleChange={this.changeState}
              value={this.state.clubs}
            />
            <Fab color="primary" aria-label="add" onClick={this.addClub} className="clubAddButton">

        <MaterialTable
          title="Clubs"
          columns={[
            { title: 'Date', field: 'scheduledDate' },
            { title: 'Status', field: 'statusDesc' },

          ]}
          data={this.state.tableClubs}
        />
      </div>
    );
  }
}

标签: javascriptreactjsmaterial-uimaterial-table

解决方案


将函数“changeDate”从箭头函数更改为普通函数解决了这个问题。我猜箭头函数正在删除回调函数的上下文


推荐阅读