ReactJS中的两个循环,而不是硬编码 [英] Two loops in ReactJS instead of hardcoding

查看:102
本文介绍了ReactJS中的两个循环,而不是硬编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 ReactJS教程井字游戏中完成额外的练习.

现在我有了以下代码:

class Board extends React.Component {
renderSquare(i) {
    return (
        <Square
            value={this.props.squares[i]}
            onClick={() => this.props.onClick(i)}
        />
    );
}

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

}

我没有用硬编码{this.renderSquare(x)} 9次,而是想用两个循环替换它们或使用map(map()),但是我写的所有内容都比硬编码差.

Instead of hardcoding {this.renderSquare(x)} for 9 times, I wanted to replace them with two loops or use map(map()) but all that I write look worse than hardcoding it.

是否有更好的方法来避免硬编码?

Is there a better way to do it and avoid hardcoding?

推荐答案

使用循环可能会更好的主要原因是因为循环更通用.

The main reason using loops could be better is because a loop is more generic.

以下是一些建议:

您可以在两个变量中保留行数和每行的平方数,这些变量可以作为循环限制,然后调整网格仅需要更新这两个变量.

You can hold the amount of rows and squares per row in two variables that can serve as loop limits and then adjusting your grid will only require updating these two variables.

将代码拆分为几种方法也可能会对其进行清理.

Splitting the code into a few methods might also clean it up.

这是一个带有循环的例子:

Here's an example with loops:

// these can also be passed in as `props` 
// if you want to use them like `<Board totalRows={3} squaresPerRow={3} squares={...}/>`
const totalRows = 3;
const squaresPerRow = 3;

class Board extends React.Component {
  renderSquare(i) {
    // ...
  }

  renderRow(row) {
    const squares = [];
    const offset = row * squaresPerRow; // this makes sure first row is 0,1,2, second row is 3,4,5, etc.
    for (let s = 0; s < squaresPerRow; s++) {
      squares.push(
        this.renderSquare(offset + s);
      );
    }
    return (
      <div className="board-row">
        {squares}
      </div>
    )
  }

  render() {
    const rows = [];
    for (let r = 0; r < totalRows; r++) {
      rows.push(
        this.renderRow(r)
      );
    }
    return <div>{rows}</div>;
  }
}

这篇关于ReactJS中的两个循环,而不是硬编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆