How to handle state of multiple buttons with react?

后端 未结 1 1279
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 04:25

I have a bootstrap grid where each grid item is populated from an array of objects but after each grid item I would like to have a vote button. How could I achieve this with

相关标签:
1条回答
  • 2021-01-03 05:04

    I have created a simple example for you:

    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>
            );
        }
    }
    

    Check the fiddle and implement it in your case.

    One more way to handle this is keeping the index of an active button in the state:

    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/

    0 讨论(0)
提交回复
热议问题