【问题标题】:React - change state of one button from 100 buttons array, and reset state of all buttons on one clickReact - 从 100 个按钮数组中更改一个按钮的状态,并一键重置所有按钮的状态
【发布时间】:2020-07-16 13:02:56
【问题描述】:

所以,我有 100 个来自数组的映射按钮,类似这样的

        {
          buttons.map((button, index) =>
            <StyledGameButton
              key={index}
              value={button}
              onClick={this.checkButton}>
              { button < 10 ? `0${button}` : button }
            </StyledGameButton>
          )
        }

我希望用户点击从 0 到 99 的所有按钮,所以当他点击例如 0 时,按钮应该改变颜色。我做了功能检查他是否点击了正确的按钮,如果是,那么我将 data-attr 添加到该按钮(这就是我更改按钮颜色的方式):

  checkButton = e => {
    const buttonId = e.currentTarget.getAttribute('value');
    const nextButton = this.state.currentButton === null ? 0 : this.state.currentButton + 1;
    if (buttonId == nextButton){
      this.setState({
        currentButton: parseInt(buttonId),
      });
      if (this.state.currentButton === 99) {
        this.gameEnd();
      };
      e.currentTarget.setAttribute('data-status', 'correct');
    }
  }

问题是我想制作重置按钮,这会将所有按钮更改为“未点击”,因此我必须一键从所有按钮中删除 data-attr。我怎样才能做到这一点?或者有没有更好的解决方案来管理单个按钮的“状态”而不创建 100 个状态?

【问题讨论】:

标签: javascript reactjs state


【解决方案1】:

100 个复选框演示

使用数组来存储状态就可以了。

const list = [...Array(100).keys()].map(x => ({ id: x }));
const App = () => {
  const [selected, setSelected] = React.useState([]); // init with empty list
  const onChangeHandler = id => () => {               // pass index/identify params
    selected.includes(id)                             // check whether been checked
      ? setSelected(selected.filter(x => x !== id))   // yes, remove
      : setSelected([...selected, id]);               // no, add
  };
  const onRemove = () => {
    setSelected([]);                                  // remove all, set to empty list
  };
  return (
    <div className="App">
      {list.map(item => (
        <input
          type="checkbox"
          key={item.id}
          checked={selected.includes(item.id)}
          onChange={onChangeHandler(item.id)}
        />
      ))}
      <br />
      <button onClick={onRemove}>Remove all</button>
      <div>{selected.join(",")}</div>
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

【讨论】:

    猜你喜欢
    • 2011-12-25
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2020-07-23
    相关资源
    最近更新 更多