我正在嘗試使用React.cloneElement()
向兒童添加道具。但是,由於陣營抱怨渲染孩子沒有鑰匙,所以我必須鍵指定給他們:指定要克隆的ReactJS元素的密鑰
const extendedChildren = children.map((child, index) => {
const unkeyedElement = React.cloneElement(child, someProps);
unkeyedElement.key = index;
return tmpElement;
});
而且他們呈現:
return (
<div>{extendedChildren}</div>
);
但我一這個錯誤:
Uncaught TypeError: Cannot assign to read only property 'key' of object '#'
有沒有一種更好的方式爲孩子分配鍵?
編輯:
Object.assign({}, unkeyedElement, { key: index })
可以解決這個問題,但我感覺這是一個反模式,因爲我把很多精力只是,我並不需要一個密鑰。歡迎任何建議。
'Object.assign'不是反模式。這是正確的做法。 –