我发现了一堆看起来重复的问题,但我似乎无法解决我遇到的这个问题。我有一个父组件:
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 方法传递给子级。 child 看起来像:
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) 我可以看到该函数正在作为 prop 传递。如果我 console.log(this.props.onDateChange) 它返回:
ƒ onDateChange(currentDate) {
this.setState({
currentDate: currentDate
});
}
我可以看到该函数及其应该执行的代码。我尝试创建一个调用 this.props.onDateChange 的方法,然后调用该方法,但它仍然不起作用。我很困惑为什么我能够让该方法作为 Prop 传递,但我无法调用它。我意识到有很多问题询问如何将函数作为 Prop 传递(我能够做到这一点),我只是无法让这个函数执行。提前致谢。
编辑:我已经更新了代码以添加以下建议。我现在没有收到任何错误,但它仍然没有按预期工作。如果/当我弄清楚时,我会报告。
最佳答案
您忘记调用箭头函数内的函数:
onDateChange={(date) => this.props.onDateChange(date)}
关于javascript - 在调用从父级作为 prop 传递的子级中的方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59326431/