2016-04-21 62 views
0
var MyComponent = React.createClass({ 
getInitialState: function() { 
    return { items: '' }; 
}, 

componentDidMount: function() { 

    this.onSuccess(); 

}, 

onSuccess: function() { 

    this.setState({ items: items }); 
}, 

render: function() { 

    return (

      <Cart items={this.state.items} > 
      <CartHeader /> 
      <CartContent /> 
      <CartFooter /> 
      </Cart> 
    ) 
    } 
}); 


window.Cart = React.createClass({ 

render: function() { 

return (

     <div> 
     Cart{this.props.children} 

     </div> 

); 
} 
}); 



window.CartHeader = React.createClass({ 

render: function() { 
return (

     <div> 
     CartHeader 
     {this.props.items} 
    </div> 

    ); 
} 
}); 



window.CartContent = React.createClass({ 

render: function() { 
return (

     <div> 
      CartContent 
      {this.props.items} 
     </div> 

); 
    } 
}); 



window.CartFooter = React.createClass({ 

render: function() { 
return (

     <div> 
     CartFooter 
     {this.props.items} 
     </div> 

); 
    } 
}); 

其中「items」是一個對象。reactJS中的父子對象傳輸

現在,我的問題是如何獲得孩子的對象的價值?

這是正確的方法嗎?其實,我對此很陌生。 如果有任何建議,請讓我知道。

我的目的是發送對象數據給每個孩子,以便將來如果我不想「cartHeader」,我可以從中刪除組件。

回答

0

三種方法可以做到:

1. <Cart items={this.state.items} > 
    Under Cart component load the child component and pass the this.props.item in each child. 

2. Use Context 

3. Use cloneElement function 

我更喜歡2選項,在這種情況下,(方案)

+0

你應該避免使用上下文時,你還有其他的選擇,有關它的更多信息https://開頭的Facebook .github.io /反應/文檔/ context.html – QoP