如何更改按钮不可依赖的React.js的值



我正在尝试构建一个井字游戏,使用类练习将道具传递给子组件并提升组件的状态,这就是为什么你可以看到我创建了4个组件。

我需要帮助的问题是,当我单击其中一个按钮时,所有按钮都会同时更改其值。

我需要让每个按钮分别显示自己的值。我声明了一个函数,并赋予它将状态从null更改为X或O的功能。

// App component 
class App extends React.Component {
constructor(props) {
super(props);

}
render() {
return (
<>
<Board />
</>
);
}
}
// Board component 
class Board extends React.Component{
constructor(props){
super(props);
this.state = {txt: 'X'};
this.change = this.change.bind(this);
}
change(){
const updt = (this.state.txt === 'X' || this.state.txt === '0') ? 'O' : 'X';
this.setState({txt: updt}); 
}
render() {
return(
<>
<div>
<Row key={'1'} value={this.state.txt} change={this.change}/>
<Row key={'2'} value={this.state.txt} change={this.change}/>
<Row key={'3'} value={this.state.txt} change={this.change}/>
</div>
</>
)
}
}
// Box component 
function Box(props){
return (
<>
<button  className='class1' onClick={props.change} >{props.value}</button>
</>
);
}
// Row component 
function Row(props){
return (
<>
<div id='myId'>
<Box change={props.change} value={props.value}/>
<Box change={props.change} value={props.value}/>
<Box change={props.change} value={props.value}/>
</div>
</>
)
}

ReactDOM.render(<App/>, document.querySelector('#root'));

所有的按钮都会更改文本,因为你实际上给它们传递了相同的值,相反,你需要创建一个行数组,每行都包含一个按钮数组,然后像我在下面一样映射到这些数组上,这就是事情的意义。我还添加了用户转向功能。

// App component 
class App extends React.Component {
constructor(props) {
super(props);

}
render() {
return (
<>
<Board />
</>
);
}
}
// Board component 
class Board extends React.Component{
constructor(props){
super(props);
this.state = {
turn:"X",
rows:[
//ROW 1 
[
{
id:"btn1",
text:"0"
},
{
id:"btn2",
text:"0"
},
{
id:"btn3",
text:"0"
},
],
//ROW 2 
[
{
id:"btn1",
text:"0"
},
{
id:"btn2",
text:"0"
},
{
id:"btn3",
text:"0"
},
],
//ROW 3 
[
{
id:"btn1",
text:"0"
},
{
id:"btn2",
text:"0"
},
{
id:"btn3",
text:"0"
},
],
]};
this.change = this.change.bind(this);
}
change(rowIndex,btnId,btnLastValue){

const updt = (btnLastValue === 'X' || btnLastValue === '0') ? 'O' : 'X';
let tempState= [...this.state.rows]
const targetBtn= tempState[rowIndex].filter(btn=>btn.id==btnId)[0]
const targetBtnIndex= tempState[rowIndex].indexOf(targetBtn)

let updateText = this.state.turn=="X" ? "X": "O"
const tempState[rowIndex][targetBtnIndex].text= updateText 

this.setState({...this.state,rows: tempState, trun:updateText }); 
}
render() {
return(
<>
<div>
{
this.state.rows.map((row,index)=><Row 
key={index} 
rowIndex={index} 
row={row} 
change={this.change}
/>
)
}
</div>
</>
)
}
}
// Box component 
function Box(props){
const {value,rowIndex,change}=props
return (
<>
<button  className='class1' onClick={e=>change(rowIndex,value.id,value.text)} >{props.value}</button>
</>
);
}
// Row component 
function Row(props){
const {row,rowIndex,change}=props
return (
<>
<div id='myId'>
{
rows.map(btn =><Box 
change={change} 
rowIndex={rowIndex} 
value={btn}
/>)
}  
</div>
</>
)
}

ReactDOM.render(<App/>, document.querySelector('#root'));

最新更新