【发布时间】:2020-10-08 21:08:08
【问题描述】:
我创建了一个最终返回 5 行和 5 列的表。
对于每个单元格,我希望在页面加载时有随机数量的不同颜色的单元格,但是目前所有单元格都保持相同的颜色。
我希望每个单元格的每次迭代都将 isLit 属性设为 true 或 false,这将确定单元格是否为不同的颜色。
关于如何做到这一点的任何建议?
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} />;
}
}
【问题讨论】:
-
你可以使用
<Cell isLit={!!Math.round(Math.random())} /> -
@Titus 是对的!重要的是您计算循环内的
Math.random。否则Math.random的结果对于所有单元格都是相同的 -
感谢您的快速回复。我应该早点问路的……哎呀!
标签: javascript reactjs array.prototype.map