繁体   English   中英

将函数传递给子组件this.props.children方法未定义

[英]Passing function to child component this.props.children method undefined

我需要使用以下函数将函数传递给this.props.children

updateBarTitle(barTItle){
   this.setState({barTItle});
}
render(){
   const children = React.Children.map(this.props.children, function (child) {
        return React.cloneElement(child, {
            updateBarTitle: this.updateBarTitle
        });
      });
   {children}
}

但是我不断收到Uncaught TypeError: Cannot read property 'updateBarTitle' of undefined

我也想问一下这是最好的方法吗? 我的目标是基于子值更新父状态。 所以我在想这样做。 传递父代现成的函数,子代将对其进行更新,或者由父代访问子代状态。 例子会很有帮助。

this在您的映射函数中未绑定正确的上下文。 您可以通过将this作为第3个参数传递来绑定它:

const children = React.Children.map(this.props.children, function (child) {
    return React.cloneElement(child, {
        updateBarTitle: this.updateBarTitle
    });
}, this);

或使用不窃取上下文的箭头功能:

const children = React.Children.map(this.props.children, (child) => {
    return React.cloneElement(child, {
        updateBarTitle: this.updateBarTitle
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM