【发布时间】:2018-01-07 07:09:33
【问题描述】:
我有一个引导网格,其中每个网格项都是从一组对象中填充的,但是在每个网格项之后我想有一个投票按钮。我如何通过分别维护每个按钮的状态来实现这一点,即当单击按钮 1 时,文本应从“投票”变为“已投票”,而其他文本仍保留为“投票”。
当一个按钮被点击的那一刻,它们都变成了'Voted'
class Items extends Component {
constructor(props) {
super(props);
this.state = { hasVoted: false };
this.OnClick = this.OnClick.bind(this);
}
OnClick() {
this.setState(prevState => ({
hasVoted: !prevState.hasVoted
}));
}
render() {
const Item = teasers.items.map(item =>
<Col key={item.nid}>
<span>
{itemType}
</span>
<a href={item.path}>
<Image src={item.image.src} title={item.productType} />
<span>
{item.Title}
</span>
<div className={teasersStyle.copy}>
{" "}{item.Copy}>
</div>
</a>
<div
className={this.state.hasVoted ? "active" : "notactive"}
onClick={this.OnClick}
>
{this.state.hasVoted ? "Voted" : "Vote"}
</div>
</Col>
);
return (
<div>
<Grid>
<Row>
{Item}
</Row>
</Grid>
</div>
);
}
}
export default Items;
【问题讨论】:
-
使
hasVoted成为每个项目的属性。 -
@IngoBürk 不确定我完全理解你的意思。像这样: hasVoted = { this.state.hasVoted }
-
您可以使您的按钮有状态,也可以将它们的
hasVoted状态存储为Items状态作为布尔数组,其索引与teasers.items中的按钮索引匹配。然后在映射teasers.items.map((item, index) =>{...})时,可以使用索引访问hasVoted状态并将属性应用到按钮。顺便说一句:您使用的是this.handleOnClick,但您的方法名为OnClick()。
标签: javascript reactjs button state