在 .map 中的每次迭代中分配不同的道具值
Assign a different prop value on every iteration within a .map
我创建了一个 table 最终 returns 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} />;
}
}
目前您正在评估 this.props.chanceLightStartsOn > Math.random()
一次并将 isLit
的相同值传递给所有 Cell
组件。
您应该做的是在 .map()
函数中检查 this.props.chanceLightStartsOn
是否大于 Math.random()
,以便在每次迭代中生成随机数。
改变
<Cell isLit={isLit} />
到
<Cell isLit={this.props.chanceLightStartsOn > Math.random()} />
我创建了一个 table 最终 returns 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} />;
}
}
目前您正在评估 this.props.chanceLightStartsOn > Math.random()
一次并将 isLit
的相同值传递给所有 Cell
组件。
您应该做的是在 .map()
函数中检查 this.props.chanceLightStartsOn
是否大于 Math.random()
,以便在每次迭代中生成随机数。
改变
<Cell isLit={isLit} />
到
<Cell isLit={this.props.chanceLightStartsOn > Math.random()} />