React+Bootstrap抱怨孩子们没有唯一的钥匙,但他们都有



我已经使用uuid为我的所有组件提供了唯一的键,因为我用map生成了90%的键(我的大部分UI都是自动生成的(。然而,React一直抱怨列表中的一些子级没有唯一的密钥。我还使用Bootstrap行和列组件来订购我的UI。

当我用React Developer工具检查我的组件时,我可以看到它们中的每一个都有一个唯一的密钥。

我给出密钥的方法是,我给组件和同一组件的内部元素一个密钥。

以下是我的组件树的一些截图,以及React抱怨的确切组件:

http://prntscr.com/tkox62http://prntscr.com/tkoxb6http://prntscr.com/tkoxf9

正如您所看到的,每个组件都有一个唯一的密钥。

错误:http://prntscr.com/tkoxpp

Row和Col是引导程序组件。

RowInCard组件:

export default function RowInCard({ elements, toggleRNumpad }) {
return (
<>
<Row key={uuid()} className="card-row">
{elements &&
elements.map((element) => {
// elements in card row
return (
<>
{element.typeOfElement === "TextField" && (
<TextField
key={uuid()}
text={element.text}
></TextField>
)}
{element.typeOfElement === "Button" && (
<Button
key={uuid()}
ID={element.ID}
></Button>
)}
</>
);
})}
</Row>
</>
);
}

按钮:

export default function Button({ ID }) {
return (
<Col
key={uuid()}
>
{ID}
</Col>
);
}

文本字段:

export default function TextField({ text }) {
return (
<Col
key={uuid()}
className="text-field card-element"
>
{text}
</Col>
);
}

通常,只有在循环中渲染的元素才需要key道具。您的ButtonTextField组件不需要密钥。然而,循环中的片段确实:

// No `key` here, it's not in a loop
<Row className="card-row">
{elements &&
elements.map((element, index) => {
return (
// In a loop here, need a `key`
<React.Fragment key={index}>
{element.typeOfElement === "TextField" && (
<TextField
// No key here, its parent is not a loop
text={element.text}
></TextField>
)}
{element.typeOfElement === "Button" && (
<Button
// No key here, its parent is not a loop
ID={element.ID}
></Button>
)}
</React.Fragment>
);
})}
</Row>

相关内容

最新更新