2016-06-24 2 views
4
내가 (소품이 예에서 할당되지 않음) 그들에게 부모 소품을 통과,이 같은 요소 반응 복제하려고

:React.cloneElement를 사용하여 여러 자식을 복제하는 방법은 무엇입니까?

React.createElement('div', 
    { 
     style: this.props.style 
    }, 
    React.cloneElement(this.props.children, null) 
) 

이 그러나 반환을 오류 다음

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

하는 경우 자식이 하나 밖에 없거나 React.cloneElement (this.props.children [0], null)를 전달하면 오류가 발생하지 않고 원하는 요소가 렌더링됩니다.

여러 요소를 어떻게 복제 할 수 있습니까?

답변

9

children props는 불투명 한 구조이므로 undefined, 배열 또는 단일 반응 요소 일 수 있습니다. 당신은 children 구조를 통해 매핑 할 React.Children utilities을 사용해야합니다

const style = this.props.style 
React.createElement('div', 
    { style }, 
    React.Children.map(this.props.children, (child => React.cloneElement(child, { style }))) 
) 
+1

노트의 작은 - 마감 누락'))'끝에 – Chris

+0

좋은 캐치 @ 크리스, 당신이 감사합니다! – Pcriulan

관련 문제