我是新来 react 的,所以我不确定这里出了什么问题...... 我正在尝试创建一个 3x3 结构的输入框。这就是我想到的
function Square(prop){
return (<input type = 'text' class='w-25' style="display:inline-block">${prop.key}</input>);
}
function Row(props){
const row =[];
for( let i=props.key*3;i<(props.key+3);i++){
row.push(<Square key ={i}/>);
}
return (row);
}
class Box extends React.Component{
constructor(props){
super(props);
this.state = {
squares: Array(9).fill(null),
xIsNext: true,
};
}
render(){
let board =[];
for( let i=0; i<3;i++){
board.push(<div><Row key={i} /></div>);
}
return (board);
}
}
ReactDOM.render(
<Box />,
document.getElementById('root')
);
但我收到错误
Warning: Each child in an array or iterator should have a unique "key" prop.
就我的 Dom 而言,这 3 行已渲染为
Any help would be greatly appreciated
更新
在尝试了下面给出的一些答案后,我最终得到了单行 4 个输入框...尽管我在循环中只指定了 3 个。有人可以解释一下为什么会这样吗?我又指定了 2 行。这是新代码
function Square(prop){
return (<input type = 'text' id={prop.value} value={'x'}></input>);
}
function Row(props){
const row =[];
for( let i=props.value*3;i<(props.value+3);i++){
const val = `${i}input`;
const key = `${i}square`;
row.push(<Square key ={key} value={val}/>);
}
return (row);
}
class Box extends React.Component{
constructor(props){
super(props);
this.state = {
squares: Array(9).fill(null),
xIsNext: true,
};
}
render(){
let board =[];
for( let i=0; i<3;i++){
const key = `${i}row`;
board.push( <Row key={key} value={i}/>);
console.log(i)
}
return (board);
}
}
ReactDOM.render(
<Box />,
document.getElementById('root')
);
最佳答案
关于javascript - 在 React 中渲染对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103491/