React - 使用三元在功能组件中应用 CSS 类

Nic*_*len 0 css classname ternary reactjs react-props

我对 React 比较陌生,正在开发 John Conway - Game of Life 应用程序。我Gameboard.js为棋盘本身(它是 的子项App.js)构建了一个功能组件,以及一个Square.js代表棋盘中单个方块的功能组件(并且是 的子项Gameboard和孙子App)。

App我有一个调用的函数alive,当用户单击它时,我想更改单个方块的颜色。App也有一个 'alive' 属性,它的状态最初设置为 false,并alive在调用时将该属性更改为 true。

这是App.js

import React, { Component } from 'react';
import './App.css';
import GameBoard from './GameBoard.js';
import Controls from './Controls.js';

    class App extends Component {
      constructor(props){
        super(props);

        this.state = {
          boardHeight: 50,
          boardWidth: 30,
          iterations: 10,
          reset: false,
          alive: false
        };
      }

      selectBoardSize = (width, height) => {
        this.setState({
          boardHeight: height,
          boardWidth: width
        });
      }

      onReset = () => {

      }

      alive = () => {
        this.setState({ alive: !this.state.alive });
        console.log('Alive function has been called');

      }



      render() {
        return (
          <div className="container">
            <h1>Conway's Game of Life</h1>

          <GameBoard
            height={this.state.boardHeight}
            width={this.state.boardWidth}
            alive={this.alive}
          />

            <Controls
              selectBoardSize={this.selectBoardSize}
              iterations={this.state.iterations}
              onReset={this.onReset}
            />

          </div>
        );
      }
    }

    export default App;
Run Code Online (Sandbox Code Playgroud)

Gameboard看起来像这样并将 props.alive 传递给Square

import React, { Component } from 'react';
import Square from './Square.js';

const GameBoard = (props) => {
    return (
      <div>
        <table className="game-board">
          <tbody>
            {Array(props.height).fill(1).map((el, i) => {
              return (
                <tr key={i}>
                  {Array(props.width).fill(1).map((el, j) => {
                    return (
                      <Square key={j} alive={props.alive}/>
                    );
                  })}
                </tr>
              );
            })}
          </tbody>
         </table>
      </div>
    );
}

export default GameBoard;
Run Code Online (Sandbox Code Playgroud)

在我的 CSS 中,我有一个名为 active 的类,如果单击它,它会更改单个方块的颜色。我怎样才能使它在Square单击 td 元素时颜色发生变化(即 CSS 类更改为活动)?

我试过这个:

import React, { Component } from 'react';

const Square = (props) => {

  return(
    <td className={props.alive ? "active" : "inactive"} onClick={() => props.alive()}></td>
  );
}

export default Square;
Run Code Online (Sandbox Code Playgroud)

CSS 看起来像这样:

.Square {
  background-color: #013243; //#24252a;
  height: 12px;
  width: 12px;
  border: .1px solid rgba(236, 236, 236, .5);
  overflow: none;

  &:hover {
    background-color: #48dbfb; //#00e640; //#2ecc71; //#39FF14;
  }
}

.inactive {
  background-color: #013243; //#24252a;
}

.active {
  background-color:  #48dbfb;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能使 .Square CSS 类始终应用于每个方块,但如果它处于活动状态,单个方块的颜色会改变?换句话说,我是否可以将Square的 td设置为始终使用 .Square CSS 类进行样式设置,然后Square可以根据 的状态是否alive为真对其中的各个元素进行适当的着色App

是否有三元方法来始终设置一个特定的 CSS 类,然后另外设置 2 个其他类中的 1 个......即始终显示 Square CSS 类,并根据逻辑/状态呈现活动或非活动?

jer*_*red 6

评论有正确的想法。

您可以使用模板文字并在其中嵌入三元条件:

return (
    <td
      className={`Square ${props.alive ? "active" : "inactive"}`}
      onClick={() => props.alive()}
    ></td>
);
Run Code Online (Sandbox Code Playgroud)

模板文字的快速复习:使用反引号包裹一个字符串,你可以通过将它包裹在${}模式中来在其中插入一个 JavaScript 表达式。作为奖励,模板文字可以跨越多行,所以不再有尴尬的字符串连接!

const myName = "Abraham Lincoln";
const myString = `Some text.
  This text is on the next line but still in the literal.
  Newlines are just fine.
  Hello, my name is ${myName}.`;
Run Code Online (Sandbox Code Playgroud)

编辑:我现在看到的更大问题是您没有将每个单元格的状态存储在任何地方。您只有一个布尔值存储在App称为alive... 您真正需要的是一个布尔数组,每个布尔值表示单个Square.

遵循“数据向下流动”的 React 原则,“活动”状态数组应该位于Appor 中。在您的情况下,您可以尝试将其保留在, 这样并且可以保持纯粹的功能组件。GameBoardAppGameBoardSquare

在内部,App您可以board在构造函数中创建一个新的二维数组 ,并0最初用值的子数组填充它:

// App.js
constructor(props){
    super(props);

    this.state = {
      boardHeight: 50,
      boardWidth: 30,
      board: [],
      iterations: 10,
      reset: false,
    };

    this.state.board = new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0));
  }
Run Code Online (Sandbox Code Playgroud)

board数组中,每个索引代表一行。所以一个简化的例子[[0, 0, 1], [0, 1, 0], [1, 1, 1]]将代表:

0 0 1
0 1 0
1 1 1
Run Code Online (Sandbox Code Playgroud)

GameBoard应该纯粹基于board传递给它的prop渲染你的单元格网格,并将每个Square它的活动值和回调函数作为 props 传递:

const GameBoard = (props) => {
    return (
      <div>
        <table className="game-board">
          <tbody>
            {this.props.board.map((row, y) => {
              return <tr key={y}>
                {row.map((ea, x) => {
                  return (
                    <Square
                      key={x}
                      x={x}
                      y={y}
                      isAlive={ea}
                      aliveCallback={this.props.alive}
                    />
                  );
                })}
              </tr>;
            })}
          </tbody>
         </table>
      </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

从那里你应该能够看到这个应用程序是如何工作的。App存储游戏状态并呈现功能组件GameBoard。在 中GameBoard,每个都Square根据其活动值进行渲染,并aliveCallback在单击时触发。aliveCallback应该根据它的和道具在 的board数组中设置适当值的状态。Appxy