[英]React - change state of one button from 100 buttons array, and reset state of all buttons on one click
所以,我有 100 个来自数组的映射按钮,就像这样
{
buttons.map((button, index) =>
<StyledGameButton
key={index}
value={button}
onClick={this.checkButton}>
{ button < 10 ? `0${button}` : button }
</StyledGameButton>
)
}
我希望用户单击从 0 到 99 的所有按钮,所以当他单击例如 0 时,按钮应该改变颜色。 我做了 function 检查他是否单击了正确的按钮,如果是,那么我将 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 个状态?
使用数组来存储 state 就可以了。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.