Javascript 将密钥分配给克隆的元素
我正在尝试使用Javascript 将密钥分配给克隆的元素,javascript,reactjs,Javascript,Reactjs,我正在尝试使用React.cloneElement()为孩子们添加道具。但是由于React抱怨渲染的子级没有密钥,因此我必须为它们分配一个密钥: const extendedChildren = children.map((child, index) => { const unkeyedElement = React.cloneElement(child, someProps); unkeyedElement.key = index; return tmpEle
React.cloneElement()
为孩子们添加道具。但是由于React抱怨渲染的子级没有密钥,因此我必须为它们分配一个密钥:
const extendedChildren = children.map((child, index) => {
const unkeyedElement = React.cloneElement(child, someProps);
unkeyedElement.key = index;
return tmpElement;
});
它们的呈现方式如下:
return (
<div>{extendedChildren}</div>
);
返回(
{扩展儿童}
);
但后来我犯了一个错误:
未捕获的TypeError:无法分配给的只读属性“key”
对象“#”
有没有更好的方法给孩子分配钥匙
编辑:
Object.assign({},unkeyedElement,{key:index})
可以解决这个问题,但我觉得这是一个反模式,因为我花了很多精力只为了一个我不需要的键。欢迎任何建议。如果您有
否则,
const extendedChildren = children.map((child, index) => {
return React.cloneElement(child, Object.assign({}, someProps, { key: index }));
});
为了一把我不需要的钥匙,我付出了很多努力
键
对反应非常重要。实际上,它不是作为prop传递给组件的,而是由React本身用来帮助协调集合。这种方法可以处理最小的DOM更改 如果您对
否则,
const extendedChildren = children.map((child, index) => {
return React.cloneElement(child, Object.assign({}, someProps, { key: index }));
});
为了一把我不需要的钥匙,我付出了很多努力
键
对反应非常重要。实际上,它不是作为prop传递给组件的,而是由React本身用来帮助协调集合。这种方法可以处理最小的DOM更改 Object.assign
不是反模式。这是正确的方法。Object.assign
不是反模式。这是正确的做法。