2016-11-24 24 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 '#'

子どもに鍵を割り当てるより良い方法はありますか?

EDIT:

Object.assign({}, unkeyedElement, { key: index })は、問題を解決することができますが、私はちょうど私が必要としないキーのための多くの努力を入れて、それはアンチパターンだ感じています。どんな提案も歓迎されます。

+0

'Object.assign'は反パターンではありません。それは正しい方法です。 –

答えて

3

あなたはObject spread用のプリセット、

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

ありがとう、それは普及したオペレータを使用する優雅な解決です。 –

関連する問題