我有这个代码:
class Board extends Component {
static defaultProps = {
nrows: 5,
ncols: 5,
chanceLightStartsOn: 0.25
};
constructor(props) {
super(props);
this.state = {
hasWon: false,
board: this.createBoard(),
counter: 0,
};
this.createBoard = this.createBoard.bind(this);
this.keyCount = this.keyCount.bind(this);
}
[...]
render() {
const mainBoard = Array.from({length: this.props.nrows}).map(() => (
<tr>
{Array.from({length: this.props.ncols}).map((x, index) => (
<Cell key={this.state.counter + 1} onClick={() => this.flipCellsAround()} isLit={this.props.chanceLightStartsOn > Math.random()} />
))}
</tr>
));
return (
<table className="Board">
<tbody>
<h1>BOARD</h1>
{mainBoard}
</tbody>
</table>
);
我希望每次迭代我的key
都增加一个,所以它是独一无二的。我尝试了很多东西,但没有成功。是否可以将函数传递给key
,然后在每次迭代中将其递增 1?
如果您不调整表的大小,您可以简单地将index
变量传递给 key prop并将其与外部map()
的索引组合在一起。 理想情况下,它将是一个与列的内容有某种逻辑联系的数字,因此 React 知道在Cell
组件发生变化时重新渲染您的列。
const mainBoard = Array.from({length: this.props.nrows}).map((ignored, rowIndex) => (
<tr>
{Array.from({length: this.props.ncols}).map((x, idx) => (
<Cell key={rowIndex * this.props.nrows + idx} onClick={() => this.flipCellsAround()} isLit={this.props.chanceLightStartsOn > Math.random()} />
))}
</tr>
));
这里有一个片段来说明这一点:
var rows = Array.from({ length: 10 });
var cols = Array.from({ length: 5 });
var mainBoard = rows.map((ignored, rowIndex, rows) => {
return cols.map((ignoredCol, colIndex, col) => {
return rows.length * rowIndex + colIndex;
})
});
console.log(mainBoard)