尝试将该方法作为 props 传递给所有 child 。但是在控制台中打印子 Prop 时,它显示未定义。
控制台输出:
Object {openLightbox: undefined, closeLightbox: undefined, setLightboxState: undefined, key: 0}
将 openLightbox、closeLightbox 和 setLightboxState 方法作为 props 传递给所有子项。将其设置在变量 childProps 中。
var Lightbox = React.createClass({
getInitialState: function(){
return { display: false };
},
componentWillMount: function(){
if (this.props.data)
this.setState(this.props.data);
},
openLightbox: function(){
this.setState({display: true});
},
closeLightbox: function(){
this.setState({display: false});
},
setLightboxState: function(obj){
this.setState(obj);
},
render: function(){
var childrenWithProps = this.props.children.map(function(child, i) {
var childProps = {
openLightbox: this.openLightbox,
closeLightbox: this.closeLightbox,
setLightboxState: this.setLightboxState,
key: i
};
console.log(childProps)
for (var j in this.state){
childProps[j] = this.state[j];
}
var childWithProps = React.cloneElement(child, childProps);
return childWithProps;
});
return (
<div>
{childrenWithProps}
</div>
);
}
});
最佳答案
.map
中的
this
引用全局范围(在浏览器中它是 window
或 undefined
如果您使用严格模式
),其中没有方法openLightbox
、closeLightbox
等。您可以为设置
this
。通过第二个参数映射
this.props.children.map(function(child, i) {
...
}, this);
___^^^^_
关于reactjs - 将方法作为 Prop 传递给所有 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37241912/