我在做游戏Tic Tac Toe,但我有个问题..
我想将数组中的元素添加到传递的位置。
我的app.js:
import React, { Component } from 'react';
import './App.css';
import Square from './Square.js';
import './Square.css';
class App extends Component {
constructor() {
super();
this.state = {
board: Array(9).fill(''),
currentUser: 'X',
position: Array(9).fill(''),
}
}
changeUser = () => {
this.setState({
currentUser: this.state.currentUser === 'X' ? "O" : "X",
})
}
render() {
return (
<div id="game">
<div id='head'>
<h5> Tic Tac Toe Jcsouz Games </h5>
</div>
<div id="board">
{this.state.board.map((v, i) => <Square position={this.state.position} value={i} key={i} changeUser={this.changeUser} currentUser={this.state.currentUser}>
{props => (<span>{props}</span>)}
</Square>
)}
</div>
</div>
);
}
}
export default App;
Square.js (我在这里做push
);
import React from 'react';
import './Square.css';
class Square extends React.Component {
constructor() {
super();
this.state = {
player: '',
}
}
changePlayer = () => {
const { changeUser, value, position, currentUser } = this.props;
position.push(currentUser);
changeUser();
if (this.state.player === '') {
this.setState({
player: this.props.currentUser,
})
}
}
render() {
return (
<div className="square" onClick={this.changePlayer}>
{this.props.children(this.state.player)}
{this.props.children(this.state.position)}
</div>
)
}
}
export default Square;
需要发生的事情:每个正方形都有它的索引(从0到8),我想要它,例如:如果我单击正方形数字0,它将它的值添加到数组中的位置0 'X','‘
我尝试这样做,但给出了错误:
会有人来帮我吗?请..。
发布于 2018-05-30 08:16:13
position.push()
方法只会添加到数组中。要影响数组的某个位置,您需要:
this.state = {
board: Array(9).fill('')
}
this.state.board[1] = 'X'
最后一行代码将把board变量第一个位置的当前值替换为一个'X‘字符,这样您就可以:
["", "X", "", "", "", "", "", "", ""]
希望能有所帮助。
更新
我的理解是slice()
方法会在数组中间插入一个元素。因此,它将会增长。我认为这不是你的目标
更新
应该始终使用setState()
函数来更新组件的状态
发布于 2018-05-30 08:06:48
您需要使用拼接函数,将项目放置到特定位置
所以你应该像这样做
position.splice(thePosition, 0, valueToBeInserted);
您可以在https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/splice中阅读它的文档
发布于 2018-05-30 08:10:04
您正在使用:
position.push(currentUser);
这会将元素'currentUser‘添加到数组中。这不是你想要的!
相反,您应该这样做:
position[i] = currentUser;
https://stackoverflow.com/questions/50594503
复制相似问题