2017-04-24 1 views
1

React.js 잘못 구성 요소를 자손에 값을 보낼 소품을 사용하여 초과 React.js : catch되지 않은 오류 RangeError : 최대 호출 스택의 크기는

const Child = props => <div onClick={ e => console.log(props.value) }>Click to see value.</div> 
const Father = props => <div>{ React.cloneElement(props.children, props) }</div> 
const GrandFather = props => <div>{ React.cloneElement(props.children, props) }</div> 

ReactDOM.render(
    <GrandFather value="This is Test"> 
    <Father> 
     <Child /> 
    </Father> 
    </GrandFather>, 
    document.getElementById('root') 
) 

내가 자손에 정보를 전송하기 위해 props를 사용하여 테스트 할 수있는 이전의 데모를 쓰기? 구성 요소. 하지만 그것은 잘못을 일으켰습니다 :

Uncaught RangeError: Maximum call stack size exceeded at Object.ReactElement.cloneElement

데모가 잘 실행 된 후에 작성하지만 오류가 발생한 원인을 알려주시겠습니까?

const Child = props => <div onClick={ e => console.log(props.value) }>Click to see value.</div> 
const Father = props => <div>{ React.cloneElement(props.children, props) }</div> 

ReactDOM.render(
    <Father value="This is Test"> 
    <Child /> 
    </Father>, 
    document.getElementById('root') 
) 

답변

0

나는 몇 가지 테스트 후이 문제를 해결에게 있습니다.

먼저, Father 구성 요소에 질문을 배치합니다.

둘째, 잘못된 정보 Maximum call stack size exceeded은 항상 무한한 무언가를 생성하여 재활용하지 않아 발생합니다.

그래서, 나는 소품에게 내가 Father에 보내 이 값 children을 가지고을 발견 한 것은 그 자체이다 - Father.

GrandFather은 소품이 있습니다

{ 
    value: "This is Test", 
    children: Father React Element 
} 

나는 또한 아버지 구성 요소로 전송됩니다 React.cloneElement(child, props), the props.children = Father React Element를 사용하는 경우.

React API를 확인한 후 .cloneElement의 세 번째 매개 변수는 복제 된 요소의 children입니다. 모든 후

, 내 솔루션입니다 : 내가 아이들 요소를 렌더링하는``React.Children.map()를 사용하여 변경 한 후

const CloneProps2Children = props => <div>{ React.Children.map(props.children, child => React.cloneElement(child, props, child.props.children)) }</div> 
const Child = props => <div onClick={ e => console.log(props.value) }>Click to see value.</div> 

export default (
    <CloneProps2Children value="This is test for many middles"> 
    <CloneProps2Children> 
     <CloneProps2Children> 
     <Child></Child> 
     </CloneProps2Children> 
    </CloneProps2Children> 
    </CloneProps2Children> 
) 
+0

구성 요소에 하위 요소가있는 경우 JSX에도 하위 구성 요소가 있습니다. 구성 요소의'props.children'은 사용자가 설정 한 소품입니다. 'React.js'가 둘 모두를 얻을 수있는 해결책을 제시 할 수 있을까요? – TomIsion

+0

키는 새로운 요소의'children' 인'.cloneElement'의 세번째 파라미터입니다. – TomIsion

0

하나의 요소 만 복제해야합니다. React.Children 배열

https://facebook.github.io/react/docs/react-api.html#cloneelement

React.cloneElement(
     element, 
     [props], 
     [...children] 
    ) 
+0

: 후

const Father = props => <div>{ React.Children.map(props.children, child => React.cloneElement(child, props, child.props.children)) }</div> 

전체 데모입니다 , 여전히 같은 질문이 있습니다. T T – TomIsion

관련 문제