gpt4 book ai didi

javascript - 如何用 react 处理多个按钮的状态?

转载 作者:行者123 更新时间:2023-12-03 13:33:08 24 4
gpt4 key购买 nike

我有一个引导网格,其中每个网格项都是从对象数组中填充的,但在每个网格项之后我希望有一个投票按钮。我怎样才能通过分别维护每个按钮的状态来实现这一点,即当单击按钮 1 时,文本应从“投票”更改为“已投票”,而其他按钮仍保持为“投票”。

点击按钮的那一刻,所有按钮都变为“已投票”

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;

最佳答案

我为您创建了一个简单的示例:

class App extends React.Component {
constructor() {
super();
this.onClick = this.onClick.bind(this);
this.state = {
arr: [
{ name: "first", isActive: true },
{ name: "second", isActive: true },
{ name: "third", isActive: true },
{ name: "fourth", isActive: true }
]
};
}
onClick(index) {
let tmp = this.state.arr;
tmp[index].isActive = !tmp[index].isActive;
this.setState({ arr: tmp });
}
render() {
return (
<div>
{this.state.arr.map((el, index) =>
<div key={index} onClick={() => this.onClick(index)}>
name: {el.name} / isActive: {el.isActive ? "true" : "false"}
</div>
)}
</div>
);
}
}

检查fiddle并在您的案例中实现它。

处理此问题的另一种方法是将事件按钮的索引保持在状态中:

class App extends React.Component {

state = {
users: [
{ name: "John" },
{ name: "Sarah" },
{ name: "Siri" },
{ name: "Jim" },
{ name: "Simon" },
],
activeIndex: 0,
}

render() {
const { users, activeIndex } = this.state;

return (
<div>
{users.map((u, i) => (
<div
className={i === activeIndex ? 'active' : ''}
onClick={() => this.setState({ activeIndex: i })}
key={u.name}
>
{u.name}
</div>
))}
</div>
)
}
}

https://jsfiddle.net/846tfe3u/

关于javascript - 如何用 react 处理多个按钮的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45420503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com