試圖將方法作爲道具傳遞給所有的孩子。但是在控制檯上打印子道具時,它顯示爲未定義。作爲道具給所有的孩子傳遞方法
控制檯輸出:
Object {openLightbox: undefined, closeLightbox: undefined, setLightboxState: undefined, key: 0}
傳遞openLightbox,closeLightbox和setLightboxState方法作爲道具給所有的孩子們。在變量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>
);
}
});