【问题标题】:Assign a different prop value on every iteration within a .map在 .map 内的每次迭代中分配不同的 prop 值
【发布时间】:2020-10-08 21:08:08
【问题描述】:

我创建了一个最终返回 5 行和 5 列的表。

对于每个单元格,我希望在页面加载时有随机数量的不同颜色的单元格,但是目前所有单元格都保持相同的颜色。

我希望每个单元格的每次迭代都将 isLit 属性设为 truefalse,这将确定单元格是否为不同的颜色。

关于如何做到这一点的任何建议?

static defaultProps = {
  nrows: 5,
  ncols: 5,
  chanceLightStartsOn: 0.25,
};

// [...]

render() {
  const isLit = this.props.chanceLightStartsOn > Math.random();

  const mainBoard = Array.from({ length: this.props.nrows }).map(() => (
    <tr>
      {Array.from({ length: this.props.ncols }).map((x, index) => (
        <Cell isLit={isLit} />
      ))}
    </tr>
  ));

  return (
    <table className="Board">
      <tbody>
        <h1>BOARD</h1>
        {mainBoard}
      </tbody>
    </table>
  );
}

Cell.js

class Cell extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(evt) {
    // call up to the board to flip cells around this cell
    this.props.flipCellsAroundMe();
  }

  render() {
    let classes = "Cell" + (this.props.isLit ? " Cell-lit" : "");

    return <td className={classes} onClick={this.handleClick} />;
  }
}

【问题讨论】:

  • 你可以使用&lt;Cell isLit={!!Math.round(Math.random())} /&gt;
  • @Titus 是对的!重要的是您计算循环内的Math.random。否则Math.random 的结果对于所有单元格都是相同的
  • 感谢您的快速回复。我应该早点问路的……哎呀!

标签: javascript reactjs array.prototype.map


【解决方案1】:

目前您只评估一次this.props.chanceLightStartsOn &gt; Math.random() 并将isLit 的相同值传递给所有Cell 组件。

您应该做的是在.map() 函数中检查this.props.chanceLightStartsOn 是否大于Math.random(),以便在每次迭代中生成随机数。

改变

<Cell isLit={isLit} />

<Cell isLit={this.props.chanceLightStartsOn > Math.random()} />

【讨论】:

  • 非常感谢@Yousaf,这很有效,很好的解释
猜你喜欢
  • 2019-12-13
  • 2020-04-04
  • 1970-01-01
  • 2023-03-25
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
相关资源
最近更新 更多