我有几个显示各种细节的 div。我打算从后端获取详细信息并将它们绑定(bind)到我的 html 部分。目前我已经硬编码了细节。这是我的 html 部分
<div className="trait_box polaroid" onClick={this.trait_select}>
<div className="main_trait_card" style={{transform: this.state.rotated ? 'rotateY(180deg)' : 'none' }}>
<div className="front_card_rotate">
<div className="trait_description_div">
<span className="trait_description">Honesty</span>
</div>
<div className="trait_img_div">
<img src={Honesty} className="trait_img"/>
</div>
<div className="block__body">
<img src={Add} className="trait_add"/>
<p className="trait_text">Honesty refers to a facet of moral character and connotes positive and virtuous attributes such as integrity, truthfulness,straightforwardness etc.. </p>
</div>
</div>
<div className="back_card_rotate front_card_rotate">
<span>Wolverine</span>
</div>
</div>
</div>
这是根据后端有多少元素重复的div。
我像这样在点击时旋转这些 div
constructor() {
super();
this.state = {rotated: false};
this.trait_select = this.trait_select.bind(this);
}
trait_select = (e) => {
this.setState({rotated: !this.state.rotated});
}
我的问题是相同的 css 类在重复,当有超过 1 个元素时,每次单击一个元素时都会旋转。因为每个元素都有相同的 css 类。如何区分我点击的元素与其他元素?
最佳答案
我认为每个 trait_box 都应该是一个组件并管理自己的状态:
class TraitBox extends Component {
constructor(props) {
super(props);
this.state = { rotate: false }
}
trait_select = (e) => {...}
render() {
return ( <div className="trait_box..." ></div> )
}
}
// and then you can import/use that component in a container
class ContainerApp extends Component {
render() {
return (
<TraitBox />
<TraitBox />
<TraitBox />
)
}
}
现在,每个 TraitBox 都可以管理自己的状态和样式
顺便说一句,你不需要这个:
this.trait_select = this.trait_select.bind(this);
如果 trait_select 是箭头函数(AF 应该自动绑定(bind)“this”)。
关于javascript - 仅将更改应用于具有相同方法名称的多个元素中的单击元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42918972/