试图将方法作为props传递给所有孩子。但是在控制台中打印子props时,它显示未定义。
控制台输出:
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>
);
}
});