Javascript 如何在更改其状态后仅渲染一个组件?

Javascript 如何在更改其状态后仅渲染一个组件?,javascript,reactjs,Javascript,Reactjs,如何仅显示一个已单击其父级的组件?运行代码时,在更改状态后,所有CardDetails组件都会呈现。是否有其他方法代替为每个组件添加唯一的onclick事件和状态 class Deck extends React.Component { constructor(props) { super(props); this.state = { cardDetails: false }; // This binding is nece

如何仅显示一个已单击其父级的
组件?运行代码时,在更改状态后,所有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'));
类组扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
cardDetails:错误
};
//此绑定是使`This`在回调中工作所必需的
this.handleClick=this.handleClick.bind(this);
this.onClick=this.onClick.bind(this);
}
onClick(){
这是我的国家({
cardDetails:是的,
//当cardDetails设置为true时,将渲染所有组件
},函数(){
console.log('cardDetails:'+this.state.cardDetails+'.this.onclick:'+this.onclick)
});
}
render(){
返回(
{ this.state.cardDetails?:空 } { this.state.cardDetails?:空 }
);} ReactDOM.render(,document.getElementById('root'));
在CardDetails组件中添加shouldComponentUpdate方法。还将状态值作为道具发送给它。然后做一些类似的事情

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

基本上,这将防止在状态更改时重新呈现CardDetails组件。

我是否正确地将
shouldComponentUpdate
方法添加到
类CardDetails extensed React.component{}
并从this.state.CardDetails更改为this.props.CardDetails?我是个新手,反应有点慢。提前感谢。保持父组件的原样。在声明Declare以便在card details组件内访问this.props.cardDetails时。因此,父组件中的任何更改都将更改props值,从而重新呈现CardDetails组件。通过在“卡详细信息”组件中返回false,可以防止重新渲染。所以当props.cardDetails值改变时,你不想渲染。是的,但它仍然渲染多个所有组件。也许我做错了什么?我的意思是有7个组件作为子组件带有
CardDetails
组件,当我单击其中一个组件时,应该呈现这一个组件。我想我之前误解了这个问题。您有一组名称,如CardDeatils1、CardDetails 2。。。到7点。单击其中一个,您需要安装或加载组件,对吗?