【发布时间】:2020-05-27 20:14:25
【问题描述】:
我正在尝试从 parent->child 传递一个回调函数,但是当渲染子组件时出现错误:TypeError: this.props.setCurrentWindow is not a function。
我试图传递函数setCurrentWindow的父组件
class Parent extends Component {
constructor(props){
super(props);
this.setCurrentWindow = this.setCurrentWindow.bind(this);
}
setCurrentWindow(){
console.log("called")
}
render(){
return(
<Child
setCurrentWindow={this.setCurrentWindow}
/>)}
}
我试图调用setCurrentWindow的子组件
class Child extends Component{
constructor(props){
super(props)
}
render(){
return(
<div
onClick={()=>{this.props.setCurrentWindow()}}>
{this.props.children}
</div>
)}
}
为什么setCurrentWindow 在这里没有被识别为函数?
【问题讨论】:
-
也许你的意思是
{this.props.setCurrentWindow}而不是{this.props.setCurrentWindow()}。 -
当我这样做时,我得到一个编译错误:
Expected an assignment or function call and instead saw an expression -
onClick={this.props.setCurrentWindow}> -
如果你更新代码,你应该解释它不是相同的代码给你有问题的错误。必须查看问题编辑历史以查看实际导致错误的原因,这非常令人困惑..
-
啊,这似乎行得通!我意识到错误在于将其包装在匿名函数中。在我的完整代码中,我有多个在此 onClick 事件上调用的函数,有没有办法在匿名箭头函数 ()=>{} 中调用它,例如
onClick={()=>{this.props.setCurrentWindow(); this.setState({...}); this.myLocalFunction()}}?
标签: javascript reactjs