繁体   English   中英

我想为特定的方形组件设置样式。

[英]I want to style a particular square component.

这是取自https://reactjs.org/的井字游戏代码,我的目的是选择特定的正方形组件。 此代码包含游戏,棋盘和正方形组件。 正方形分量在Board方法中渲染了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;
}

您可以使用CSS的' :nth-of-type() '方法设置特定正方形的样式。 例如,对于您的情况,如果您只想将第一个正方形设为红色,则可以执行以下操作:

.square:nth-of-type(1) {
  background-color: red;
}

如果要对正方形单击进行样式设置,则必须保存单击的正方形,因此应将正方形的索引保存为以下状态:

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 ,我们可以为您提供更多帮助。 好吧,首先我描述算法。我们知道this.props.onClick(i)传递被点击的正方形的索引。 同样,我们要为被单击的正方形设置样式,因此首先我们必须存储被单击的正方形的索引。我们将其存储在Square的父级中,也许是Board或Game组件中。 因此单击正方形中的图像,然后将索引存储在state中。因此,我们具有被单击的正方形的索引。然后将这个数字传递给带有selectedSquareIndex正方形,以便正方形可以知道单击了哪个正方形并使用self和index来检查该数字如果这些数字相等,则单击此正方形,然后为其添加一个类名。

Updatae 2

在这里,您可以看到我为单击添加颜色以添加正方形的效果: 代码沙箱,但您可以更改app.js中的specifixIndex来匹配点击或您想要的其他内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM