我正试图在React中创建自己的生命游戏。目前已经创建了一个带有div的地图,将来在我完成项目时将是单独的单元格。我还想将click事件附加到每个单元格,但出于某种原因,当我单击单个单元格时,整个单元格集都会受到影响。你能检查一下为什么会这样吗?另外,如果我的方法是正确的,你能告诉我吗?这是我的index.js代码:
class Board extends React.Component {
constructor(props){
super(props);
this.state = {isToggleOn: true};
this.changeState = this.changeState.bind(this);
}
changeState() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
createMap = (cols, total) => {
let table = []; let nL = ''; let idRow = 0; let idCol = 0;
for (let i = 0; i < total; i++) {
idCol++;
if (i%cols === 0){
nL = 'newLine';
console.log(i%cols);
idRow += 1;
idCol = 0;
}
else {
nL = '';
}
let toggledBackground = (this.state.isToggleOn ? 'test' : '');
table.push(<div id={"row-"+idRow+"-"+idCol} className={nL+" square "+toggledBackground} onClick={this.changeState}></div>);
}
return table;
}
render() {
return(
<div>
{this.createMap(COLS, FIELDS)}
</div>
);
}
}
答案 0 :(得分:1)
所有这些都突出显示,因为它们都共享相同的状态,最简单的解决方案是为方块创建一个单独的组件,并将所需的数据作为道具传递。
这将允许您为每个单元格分别设置状态。
答案 1 :(得分:0)
我认为FIELDS
是单元格的总数(例如10x10板,这将使FIELDS = 100)。如果是这种情况,那么您可以将每次迭代的当前索引绑定到您正在推送的所述单元格。
这样,您就可以知道点击了哪个单元格。
onClick={() => this.changeState(i)}
您还需要在实际的函数声明中添加一个参数,并保存该特定单元格的状态:
changeState(index) {
this.setState(prevState => {
let arr = prevState.cellStates.slice();
arr[index] = !arr[index];
return {cellStates: arr};
});
}
当然,这需要你有一个数组,而不是一个布尔值:
this.state = {cellStates: Array(FIELDS).fill(false)};
最后是你的风格:
let toggledBackground = (this.state.cellStates[i] ? 'test' : '');