2016-12-29 102 views
0

如何只顯示一個<CardDetails />組件,其父母被點擊?當我運行我的代碼時,在更改狀態後,所有CardDetails組件都呈現。是否有另一種方式,而不是爲每個組件添加獨特的onclick事件和狀態?如何在更改其狀態後僅渲染一個組件?

class Deck extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
     cardDetails: false 
     }; 
     // This binding is necessary to make `this` work in the callback 
     this.handleClick = this.handleClick.bind(this); 
     this.onClick = this.onClick.bind(this); 
    } 
    onClick() { 
     this.setState({ 
     cardDetails: true, 
     // when cardDetails is set as true, all <CardDetails /> components are rendered 
     }, function() { 
     console.log('cardDetails: ' + this.state.cardDetails + '. This.onclick: ' + this.onClick) 
     }); 
    } 
    render() { 
     return (< div className = "deck-container" > < div className = "chosen-cards" > 
     <CardHistory onClick = { 
       this.onClick 
      } > { 
       this.state.cardDetails ? < CardDetails/> : null 
      } < /CardHistory> 
      < CardHistory onClick = {this.onClick} > { 
       this.state.cardDetails ? < CardDetails/> : null 
      } < /CardHistory> </div > < /div>);}} 
      ReactDOM.render(<Deck> < /Deck>,document.getElementById('root')); 

回答

0

在CardDetails組件中添加一個shouldComponentUpdate方法。也將狀態值作爲道具發送給它。然後做類似

shouldComponentUpdate(nextProps, nextState) { 
    return (nextprops.cardDetails != this.props.cardDetails); 
} 

基本上,這將防止重新呈現的CardDetails組件每當狀態發生變化。

+0

我收到你了嗎?我應該添加'shouldComponentUpdate'方法來'類CardDetails擴展React.Component {}',並從this.state.cardDetails更改爲this.props.cardDetails?我是新來的反應,它有點慢。提前致謝。 – zaebalo

+0

保持父組件原樣。在聲明聲明時,可以訪問this.props.cardDetails。因此,父組件中的任何更改都會更改道具值,從而重新渲染CardDetails組件。您可以通過在卡片詳細信息組件中返回false來防止重新渲染。那麼你什麼時候不想渲染就是在props.cardDetails值發生變化的時候。 –

+0

是的,但它仍然使用呈現多個所有組件。也許我做錯了什麼? – zaebalo

相關問題