2016-12-29 105 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

相关问题