我想显示更多信息onclick,但我有不同的div来显示/隐藏。 所以。我是这样做的: 州是:
this.state = {
showMore: false,
showRewards: false,
fees: false,
showFees: false
};
其中一个div:
<div className='some'> <h3 >Rewards <i className="icon-im-rewards"></i></h3> <h5 className="showMoreDetails" onClick={ () => this.show('rewards') }>{ showRewards ? '-' : '+' } { showRewards ? 'Show Less' : 'Show More' }</h5> { showRewards && detail.rewards.reward.map((name, i) => <p key={i}> { name }</p> ) } </div>
功能:
show(name){ 让{showMore,showRewards,showFees} = this.state;
if (name === 'hightlights' && showMore === false) {
this.setState({
showMore: true
});
} else {
this.setState({
showMore: false
});
}
if (name === 'rewards' && showRewards === false) {
this.setState({
showRewards: true
});
} else {
this.setState({
showRewards: false
});
}
if (name === 'fees' && showFees === false) {
this.setState({
showFees: true
});
} else {
this.setState({
showFees: false
});
}
这太长,太丑了,不能正常工作(我一次只能看到一个扩展的div)如何改进它?
答案 0 :(得分:2)
这是一种更好,更清洁的方式:
function show (name) {
let { showMore, showRewards, showFees } = this.state;
showMore = name === 'hightlights' && showMore === false;
showRewards = name === 'rewards' && showRewards === false;
showFees = name === 'fees' && showFees === false;
this.setState({
showFees,
showRewards,
showMore
});
答案 1 :(得分:0)
如果你能向我们展示细节和结构的结构可能会更容易。奖励。我猜你在这里映射一个单独的元素,这就是它打印单个元素的原因。但是,请尝试更改此行,
detail.rewards.reward.map((name, i) => <p key={i}> { name }</p> )
替换为以下代码:
detail.rewards.map((reward, i) => <p key={i}> { reward.name }</p> )