代码之家  ›  专栏  ›  技术社区  ›  Nick Kinlen

React—使用三元函数在函数组件中应用CSS类

  •  0
  • Nick Kinlen  · 技术社区  · 8 年前

    我是一个比较新的反应和工作的约翰康威-游戏的生活应用程序。我已经建立了一个 Gameboard.js 电路板本身的功能组件(它是 App.js )和一个 Square.js 表示板中单个正方形的功能组件(是 Gameboard 还有我的孙子 App

    应用程序 我有一个函数叫做 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;
    

    看起来像这样然后就过去了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;
    

    方块字

    import React, { Component } from 'react';
    
    const Square = (props) => {
    
      return(
        <td className={props.alive ? "active" : "inactive"} onClick={() => props.alive()}></td>
      );
    }
    
    export default Square;
    

    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;
    }
    

    如何使.Square CSS类始终应用于每个方块,但如果它处于活动状态,则单个方块的颜色会发生更改?换句话说,我可以设置 可根据是否 是真的吗 应用程序

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

    3 回复  |  直到 8 年前
        1
  •  4
  •   jered    8 年前

    你需要一个 template literal 并在其中嵌入三元条件:

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

    ${} 图案。作为奖励,模板文本可以跨越多行,所以没有更多的尴尬字符串串联!

    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}.`;
    

    :我现在看到的更大的问题是,没有将每个单元格的状态存储到任何位置。只有一个布尔值存储在 App alive 布尔值,每个布尔值代表一个 Square .

    应用程序 GameBoard "the data flows down" 应用程序 游戏板 可以保持纯粹的功能组件。

    应用程序 你可以创建一个新的二维数组, 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));
      }
    

    数组中,每个索引表示一行。一个简单的例子 [[0, 0, 1], [0, 1, 0], [1, 1, 1]]

    0 0 1
    0 1 0
    1 1 1
    

    游戏板 应该完全基于 道具传给它,每一个都传给它 方块字 它的活动值和回调函数作为道具:

    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>
        );
    }
    

    从那里你应该可以看到这个应用程序将如何工作。 存储游戏状态并呈现功能组件 游戏板 游戏板 方块字 aliveCallback 单击时。 aliveCallback公司 应用程序 x y 道具。

        2
  •  0
  •   Shubham Yerawar    8 年前

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

    请参考这个 code

        3
  •  0
  •   xadm    8 年前

    标题问题不是“不工作”的真正原因

    类名={props.alive ? "活动“:“非活动”}

    是正确的 ,不需要使用模板文本。

    您可以通过多种方式编写/使用它:

    className={'Square '+ (props.alive ? 'active' : 'inactive')}
    

    为真实起见,没有必要使用'非活动'作为'广场'有相同的背景色。

    className={'Square '+ (props.alive ? 'active' : null)}
    

    className={'square '+ (props.alive && 'active')}
    

    当然,您可以在返回之前在纯js中“计算/准备”值

    const Square = (props) => {
      let classes = ['Square','bb']
      if( props.alive ) classes.push('active')
      classes = classes.join(' ')
      return (
        <h1 className={classes}>Hello</h1>
      )};
    

    docs 或者在google上搜索“react css in js”。

    推荐文章