javascript - 在 React 中渲染对象数组

标签 javascript html reactjs

我是新来 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')
  );

最佳答案

这里需要移动key属性:

board.push(<div key={i}><Row /></div>);

因为key应该位于数组中每个元素的外部元素

关于javascript - 在 React 中渲染对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103491/

相关文章:

javascript - history.createBrowserHistory 不是函数 - React js

javascript - 为什么 `yield`的场景中必须加分号

Javascript:数组循环并输出文本

html - 如何在没有 colspan 的情况下合并/组合 HTML 表格单元格

html - 选择不适用于 Ionic Framework 的默认选项

html - 流体高度受限图像 HTML

javascript - 是否可以在 React Native 中从其无状态组件子级更改父级的状态?

JavaScript OOP 私有(private)变量

javascript - Chrome打包应用存储错误

css - 滚动时在 React Sticky 中制作一个 Material UI 组件(不是 AppBar)