井字反应
Tic tac toe React
我有两个组成部分。
Parent:
export default class GameBoard extends React.Component{
constructor(props){
super(props);
this.state={
boardPattern:[
' ',' ',' ',
' ',' ',' ',
' ',' ',' '
],
turn: "",
winner: null
}
}
handleClick(i){
console.log(i);
this.state.board[i]=this.state.turn
this.setState({
board:this.state.board,
turn: this.state.turn==='./images/x.ico'?'./images/y.ico':'./images/x.ico'
})
}
render() {
return (
<div>
{this.state.board.map(function(value, i){
return <Square key={i} turn={this.state.turn} onChange={()=>this.handleClick(i)}/>
}.bind(this))}
</div>
)
}
}
Child:
export default class Square extends React.Component{
handleClick = e => {
if ( typeof this.props.onTurnChange === 'function'){
this.props.onChange();
}
};
render(){
return <div className='Square' onClick={this.handleTurnChange}>
<img src={this.props.turn}></img>
</div>
}
}
我对 handleClick 函数有疑问。现在,当我单击每个方块时,每个方块中的状态 'turn'(添加源图像)都会发生变化。我怎样才能让图像只出现在我点击的广场上?
好吧,我认为问题是你做不到 this.state.board[i]=this.state.turn
不使用 setState 就无法设置状态值。
尝试复制棋盘,更新它并使用新值设置状态
像这样
const updatedBoard = this.state.board.slice();
updatedBoard[i] = this.state.turn;
this.setState({board: updatedBoard});
在你的例子中,我没有看到电路板在哪里初始化?我只看到板子的图案是不变化就不该有的状态
希望对您有所帮助!
我有两个组成部分。 Parent:
export default class GameBoard extends React.Component{
constructor(props){
super(props);
this.state={
boardPattern:[
' ',' ',' ',
' ',' ',' ',
' ',' ',' '
],
turn: "",
winner: null
}
}
handleClick(i){
console.log(i);
this.state.board[i]=this.state.turn
this.setState({
board:this.state.board,
turn: this.state.turn==='./images/x.ico'?'./images/y.ico':'./images/x.ico'
})
}
render() {
return (
<div>
{this.state.board.map(function(value, i){
return <Square key={i} turn={this.state.turn} onChange={()=>this.handleClick(i)}/>
}.bind(this))}
</div>
)
}
}
Child:
export default class Square extends React.Component{
handleClick = e => {
if ( typeof this.props.onTurnChange === 'function'){
this.props.onChange();
}
};
render(){
return <div className='Square' onClick={this.handleTurnChange}>
<img src={this.props.turn}></img>
</div>
}
}
我对 handleClick 函数有疑问。现在,当我单击每个方块时,每个方块中的状态 'turn'(添加源图像)都会发生变化。我怎样才能让图像只出现在我点击的广场上?
好吧,我认为问题是你做不到 this.state.board[i]=this.state.turn
不使用 setState 就无法设置状态值。
尝试复制棋盘,更新它并使用新值设置状态
像这样
const updatedBoard = this.state.board.slice();
updatedBoard[i] = this.state.turn;
this.setState({board: updatedBoard});
在你的例子中,我没有看到电路板在哪里初始化?我只看到板子的图案是不变化就不该有的状态
希望对您有所帮助!