我发现了一堆看似重复的问题,但我似乎无法解决我遇到的这个问题。我有一个父组件:
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
//some other props
currentDate: moment()
};
componentDidMount() {
this.fetchData();
}
fetchData() {
this.setState({
//set some state here
});
//Some Api call
}
onDateChange(currentDate) {
this.setState({
currentDate
});
}
//doing some stuff to render a table
return (
<div>
<ChildComponent
currentDate={this.state.currentDate}
onDateChange={(date) => this.onDateChange(date)}
/>
{currentView}
</div>
);
}
render() {
return (
<div>
//renders table
</div>
);
我能够将 onDateChange 方法传递给孩子。孩子看起来像:
class Child extends Component {
constructor(props) {
super(props);
this.state = {
currentDate: this.props.currentDate,
focused: false
};
render() {
return (
<div className="form-group">
<SingleDatePicker
date={this.state.currentDate}
onDateChange={(date) => this.props.onDateChange(date)}
focused={this.state.focused}
onFocusChange={({ focused }) => this.setState({ focused: focused })}
/>
</div>
);
无论出于何种原因,我都无法调用 onDateChange 方法。如果我 console.log(this.props) 我可以看到该函数作为道具传递。如果我 console.log(this.props.onDateChange) 它返回:
ƒ onDateChange(currentDate) {
this.setState({
currentDate: currentDate
});
}
我可以看到它应该执行的函数和代码。我尝试创建一个调用 this.props.onDateChange 的方法,然后调用该方法,但它仍然不起作用。我很困惑为什么我能够让方法作为道具传递,但我不能调用它。我意识到有很多问题询问如何将函数作为道具传递(我能够做到这一点)我只是无法执行此函数。提前致谢。
编辑:我已更新代码以添加以下建议。我现在没有收到任何错误,但它仍然没有按预期工作。如果/当我弄清楚时,我会报告。