简体   繁体   English

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

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

I need to pass a function to this.props.children with the following. 我需要使用以下函数将函数传递给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}
}

But I keep getting Uncaught TypeError: Cannot read property 'updateBarTitle' of undefined . 但是我不断收到Uncaught TypeError: Cannot read property 'updateBarTitle' of undefined

Also I would like to ask would this be the best approach? 我也想问一下这是最好的方法吗? My goal here is to update the parent state based on a child value. 我的目标是基于子值更新父状态。 So I was thinking either do this. 所以我在想这样做。 Pass a parent ready made function then the child will update that, or access the child state by the parent. 传递父代现成的函数,子代将对其进行更新,或者由父代访问子代状态。 Examples would be of great help. 例子会很有帮助。

this in your mapping function is not bound the correct context. this在您的映射函数中未绑定正确的上下文。 You can bind it by passing this as 3-rd argument: 您可以通过将this作为第3个参数传递来绑定它:

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

or use arrow function which does not steal context: 或使用不窃取上下文的箭头功能:

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