如何用React处理多个按钮的状态?

我有一个Bootstrap网格,其中每个网格项目都是从一组对象中填充的,但是在每个网格项目之后,我都希望有一个投票按钮。我如何通过分别保持每个按钮的状态来实现这一点,即单击按钮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>

);

}

}

检查小提琴并根据您的情况实施。

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

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/

以上是 如何用React处理多个按钮的状态? 的全部内容, 来源链接: utcz.com/qa/413834.html

回到顶部