0

抱歉,如果这看起来很费力,但我整天都在谷歌上搜索。我正在尝试使用日期选择器进行选择时更改日期的状态。我可以通过执行以下操作使此功能正常工作:

onDateChange={currentDate => this.setState({currentDate: currentDate})}

但是如果我尝试把它变成一个函数:

onDateChange(currentDate) {
this.setState({currentDate: currentDate});

}

然后将该函数传递给 onDateChange:

onDateChange={this.onDateChange}

这将返回“无法设置未定义的状态。我这样做的原因是因为我需要 onDateChange 函数在父组件中执行,然后将该道具传递给该组件。但我什至无法让该函数在子组件中工作组件。我尝试过使用箭头函数,但我很难过。有人可以告诉我为什么这不能作为函数工作吗?

更新:

解决了

onDateChange={this.onDateChange} changed to {this.onDateChange.bind(this)}
4

1 回答 1

0

第一个示例中的箭头(或“胖箭头”)通过了正确的this范围。Thethis被定义为你所期望的,并且this有一个setState方法,所以它可以工作。

在第二个示例this中,最终不是您所期望的(即undefined),因此它没有setState方法并且失败,从而导致您报告的错误。

如果您将以下绑定添加到构造函数,我相信您的第二个示例将得到解决:

class A extends Component {
  constructor(props) {
    ...
    this.onDateChange = this.onDateChange.bind(this);
    ...
  }
}

您也可以this在实例化子组件时进行绑定。那将是这样的:

   <Child ... onDateChange={this.onDateChange.bind(this)} ... />

来源:https ://reactjs.org/docs/faq-functions.html#how-do-i-bind-a-function-to-a-component-instance

于 2019-12-12T21:36:21.953 回答