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'));
我收到你了吗?我应该添加'shouldComponentUpdate'方法来'类CardDetails扩展React.Component {}',并从this.state.cardDetails更改为this.props.cardDetails?我是新来的反应,它有点慢。提前致谢。 – zaebalo
保持父组件原样。在声明 声明 时,可以访问this.props.cardDetails。因此,父组件中的任何更改都会更改道具值,从而重新渲染CardDetails组件。您可以通过在卡片详细信息组件中返回false来防止重新渲染。那么你什么时候不想渲染就是在props.cardDetails值发生变化的时候。 –
是的,但它仍然使用 呈现多个所有组件。也许我做错了什么? –
zaebalo