javascript - 如何在数组内的索引中添加元素? ReactJs

标签 javascript reactjs

我正在玩 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(我在其中进行推送);

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;

需要发生什么:每个方 block 都有它的索引(从 0 到 8),我想要它,例如:如果我单击方 block 数字 0,它会将其值添加到数组中的位置 0 [' X','','','','','','','',''],或者如果我单击方格 4,位置 4 ['','','','X ','','','','','']。

我尝试这样做,但出现错误: enter image description here

有人可以帮助我吗?请..

最佳答案

position.push() 方法只会添加到数组中。要影响数组的某个位置,您需要:

this.state = {
 board: Array(9).fill('') 
}

this.state.board[1] = 'X'

最后一行代码将用“X”字符替换 board 变量第一个位置的当前值,如下所示:

["", "X", "", "", "", "", "", "", ""]

希望有帮助。

更新

我的理解是,slice() 方法会将一个元素插入到数组的中间。结果,它会增长。我认为这不是你的目标

更新

您应该始终使用setState()函数来更新组件的状态

关于javascript - 如何在数组内的索引中添加元素? ReactJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594503/

相关文章:

javascript - 组 JS 事件

javascript - React-Router:没有找到路由?

reactjs - 使用 Travis for React 如何不将警告视为错误

javascript - React 事件和 DOM 事件有什么区别?

javascript - AWS elastic beanstalk,在 Django 中提供多个静态文件

javascript - 用于信号处理的奇函数?

javascript - 使用 Javascript 检测内容是否适合 div

node.js - 从父文件夹导入时,类型错误 : Super expression must either be null or a function, 未定义

reactjs - 在 map 函数中渲染会导致 JsLint 错误,预期是赋值或函数调用,而是看到了表达式?

JavaScript 在 IE8 中出错,但在 IE 10 中没有