2016-11-24 46 views
0

我正在嘗試使用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 spread
+0

'Object.assign'不是反模式。這是正確的做法。 –

回答

3

const extendedChildren = children.map((child, index) => { 
    return React.cloneElement(child, { ...someProps, key: index }); 
}); 

否則,

const extendedChildren = children.map((child, index) => { 
    return React.cloneElement(child, Object.assign({}, someProps, { key: index })); 
}); 

I put much effort just for a key that I don't need

key是反應非常重要。實際上它不是作爲道具傳遞給組件的,而是由React自己用來協助館藏的調和。這樣React可以處理最小的DOM更改。

+0

謝謝,這是一個使用擴展運算符的優雅解決方案。 –