javascript - 我想设计一个特定的方形组件。

标签 javascript html css reactjs

这是井字游戏的代码,取自https://reactjs.org/我的目标是选择特定的方形组件。 此代码包含游戏、棋盘和方形组件。 方 block 组件在棋盘方法中渲染了9次。而整个棋盘在游戏组件中渲染 那么有没有一种方法可以专门突出显示/设置特定方形组件的样式。

function Square(props) {
      return (
        <button  className="square" onClick={props.onClick} >
          {props.value}
        </button>
      );
    }





class Board extends React.Component {

 renderSquare(i)


{
return (
  <Square

    value={this.props.squares[i]}
    onClick={() => this.props.onClick(i)}

  />
);


 }

此渲染函数正在创建 9 个正方形(3X3 网格)

 render() 
{


return (
  <div>

    <div className="board-row"  >
      {this.renderSquare(0)}
      {this.renderSquare(1)}
      {this.renderSquare(2)}
    </div>
    <div className="board-row">
      {this.renderSquare(3)}
      {this.renderSquare(4)}
      {this.renderSquare(5)}
    </div>
    <div className="board-row">
      {this.renderSquare(6)}
      {this.renderSquare(7)}
      {this.renderSquare(8)}
    </div>
  </div>
);


 }
}


class Game extends React.Component {


constructor(props) {
super(props);
this.state = {
  history: [{ squares: Array(9).fill(null), }],
  xIsNext: true,
  count:0,


   };
  }






  reset()




{
    const history = this.state.history;
    const curr= history[history.length -1];
    console.log(curr);
    const a =curr.squares.fill(null);
    this.setState({history: history.concat([{
        squares: a,
      }])});     
    this.state.count=0;
     }









 handleClick(i)


{


const history = this.state.history;
const current= history[history.length -1];
const squares = current.squares.slice();

if(calculateWinner(squares) || squares[i] )
{

  return;



 }



 this.setState({count:this.state.count+1});


squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({history: history.concat([{
    squares: squares,
  }]),
     xIsNext: !this.state.xIsNext,
              });




}



  render() {
const history =  this.state.history;
const current= history[history.length-1];
const winner=calculateWinner(current.squares);

let status;
if(winner)
  {
  status= 'winner: '+ winner;

  }if(!winner)
    {

    status = 'Next player:'  + (this.state.xIsNext ? 'X' : 'O') ;
    }
if(!winner && this.state.count==9)
  {
    status ="game tied";
  }


return (
  <div className="game">
    <div className="game-board">
      <Board 
        squares={current.squares}
        onClick={(i) => this.handleClick(i)}
        />
    </div>
    <div className="game-info">
      <div>{status  }</div>
      <ol><button onClick={() => this.reset() }>{/* TODO */"reset" }</button></ol>
    </div>
  </div>
);


 }
}





ReactDOM.render(


 <Game />,
  document.getElementById('root')
);

此函数包含获胜逻辑 我如何设计一个特定的方形组件

function calculateWinner(squares) {



const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],];



 for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
  return squares[a];
}
  }

      return null;
}

CSS文件

body {
  font: 14px "Century Gothic", Futura, sans-serif;
  margin: 20px;
}

ol, ul {
  padding-left: 30px;
}

.board-row:after {
  clear: both;
  content: "";
  display: table;
}

.status {
  margin-bottom: 10px;
}


.square {
  background: #FFF;
  border: 1px solid #999;
  float: left;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 34px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 34px;
}

.square:focus {
  outline: none;
}

.kbd-navigation .square:focus {
  background: #ddd;
}

.game {
  display: flex;
  flex-direction: row;
}

.game-info {
  margin-left: 20px;
}

最佳答案

如果你想在方 block 点击时设置样式,你必须保存点击了哪个方 block ,所以你应该将方 block 的索引保存在这样的状态中:

class Board extends React.Component {

 renderSquare(i)


{
return (
  <Square
    selectedSquareIndex={this.state.squareSelected} {/* here we pass square index*/}
    value={this.props.squares[i]}
    onClick={() => this.props.onClick(i)}

  />
);


 }

然后在 Square 中:

function Square(props) {
      return (
        <button  className={["square",
         'selectedSquare':props.value === props.selectedSquareIndex //if true we add style 
     ]} onClick={props.onClick} >
          {props.value}
        </button>
      );
    }

在 CSS 中

.selectedSquare{background-color:red;}

但是当这种情况发生在广场时如何设置状态:

onClick={() => this.props.onClick(i)

在 onClick 中跟踪它。

更新 1 首先,如果你创建一个 Code Sandbox对我来说,我可以为您提供更多帮助。 好的,首先我描述一下算法。我们知道 this.props.onClick(i) 传递被点击的方 block 的索引。另外,我们想要设置被点击的方 block 的样式,所以首先我们必须存储被点击的方 block 的索引。我们将它存储在 Square 的父级中,可能是 Board 或者 Game 组件。所以点击正方形中的图像然后我们将索引存储在状态中。所以我们有被点击的正方形的索引。然后我们将这个数字传递给带有 selectedSquareIndex 的正方形所以正方形可以知道哪个正方形被点击并检查这个数字带有 self 索引,如果这些数字相等,则意味着这个方 block 被点击,我们给它添加一个类名。

更新数据 2

在这里您可以看到我通过单击为正方形添加颜色所做的工作: Code Sandbox 但您可以更改 app.js 中的 specifixIndex 以获取命中或其他您想要的内容。t

关于javascript - 我想设计一个特定的方形组件。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53046582/

相关文章:

javascript - 在 html 段落中打印对象属性

javascript - 合理安排推荐部分的文字

css - 仅更改某些链接的颜色 WordPress

javascript - 在 Node JS 中仅使用包含数据的变量的正确方法是什么?

javascript - 折线简化

jquery - 在 jquery 中使用 appendTo 的正确方法

html - 使用纯 CSS 创建点击多级下拉菜单

javascript - 如何使用 JavaScript 在 &lt;input&gt; 中显示 "suggestion"?

javascript - 如何添加延迟到现有 $.when 的新 jquery?

c# - ASP.NET 通过其部分 ID 查找控件