到目前为止,我的代码在单击时将G
放置在所选框中。但是这次,我也想在单击它时将其删除。
我的代码在做什么错,我该如何解决?
这是我的代码:
import React, { Component } from 'react';
import './Main.css';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
board: Array(3).fill(''),
symbol: 'G',
deleted: ''
}
}
circClicked(box) {
this.setState({
symbol: this.state.board[box.dataset]
});
box.innerText = this.state.symbol;
if(this.state.board[box.dataset] === this.state.symbol) {
for (let i = 0; i < this.state.board.length; i++) {
let s = this.setState({board: this.state.board[i]});
s--;
}
}
}
render() {
return(
<div id="game">
<div id="board" onClick={(e) => this.circClicked(e.target)}>
<div className="circ"></div>
<div className="circ"></div>
<div className="circ"></div>
</div>
</div>
);
}
}
export default Main;
答案 0 :(得分:2)
请考虑修改您的方法,以便您委派负责渲染/填充UI的责任。这将使UI的行为更可预测。
也许这样对您有用吗?
import React, { Component } from 'react';
import './Main.css';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
board: Array(3).fill(''),
symbol: 'G',
deleted: ''
}
}
circClicked(index) {
// Clone the board array
const board = [...this.state.board]
// Assign the next value to be shown in this "circ" element
board[index] = board[index] ? '' : this.state.symbol
// Update the render values to be displayed
this.setState({ board });
}
render() {
return(
<div id="game">
<div id="board">
<div className="circ" onClick={(e) => this.circClicked(0)}>{ this.state.board[0] }</div>
<div className="circ" onClick={(e) => this.circClicked(1)}>{ this.state.board[1] }</div>
<div className="circ" onClick={(e) => this.circClicked(2)}>{ this.state.board[2] }</div>
</div>
</div>
);
}
}
export default Main;