2016-10-25 13 views
0

구성 요소 인 Parent를 가져 와서 다른 구성 요소 인 Child를 주입합니다.Redux를 사용하여 상위 구성 요소의 하위 구성 요소를 읽는 중

class Parent extends Component { 
render(){ 
    //something like this 
    <div className={this.props.children.foo}> 
     {this.props.children} 
    </div> 
} 

@edit

후 :

function mapStateToProps(state) { 
    return { 
    foo : 'some-value' 
    } 
} 

내가 요소 그런 부모에 foo으로 접근하고 싶습니다 :

아이는 다음과 같이 정의 소품을 가지고 이것을 사용하여 React.Children.toArray 나는 자식을 배열로 가져 왔고 forEach -it입니다.

그러나 소품은 child.props에 없습니다.

누락 된 것이 있습니다. 누구나 아이디어가 있으십니까? 그것은

render() { 
    this.props.children.forEach((component) => { 
    console.log(component.props.foo); 
    }) 

    return ...; 
} 

에 루프가 this

+0

네,하지만 mapStateToProps 반환 No 재산권 –

+0

안녕하세요, 개발자 도구 반응하여 내가 사용 항상 연결 구성 요소가 될 것 'this.props.children'돌아 오는 것을이 눈치없는 내가 (반응-REDUX 라이브러리 참조) 실제 문제는 정의한 구성 요소 인 Connect의 하위 항목을 얻는 것입니다. –

+0

연결 메서드에는 "withRef"옵션이 있습니다. 기본적으로 래핑 된 구성 요소에 액세스하게됩니다. 기본값은 false입니다. https://github.com/reactjs/react-redux/blob/master/docs/api.md –

답변

0

당신이해야 할 것은 단일 노드 또는 여러 노드가 될 수 있습니다. 단일 노드 인 경우 props에 직접 액세스하고 map을 사용하여 하위 노드를 반복하고 porps을 반환합니다.

희망이 도움이됩니다.

render() { 
    const childProps = ! this.props.children instanceof Array 
    ? this.props.children.props.foo //returns foo if child is a single node 
    : this.props.children.map(child => child.props.foo) // returns array of foo if children is a multiple nodes. 

    console.log(childProps) 

    return ...; 
} 
+0

소리는 유망하지만 아이들을 통해 반복 할 수는 없습니다. 그것은 forEach가 함수가 아니라고 말합니다. 'for of '도 시도하면 오류가 발생합니다. –

+0

이전에 자식 속성의 유형 (배열, 객체 등)을 확인할 수 있으므로 원하는 속성을 검색하는 방법에 대한 단서가 있습니다. –

+0

this.props.children을 componentDidMount 메소드에 반복 해 보았습니까? –

0

당신의 아이들을 봐 this.props.children 여러 구성 요소가 될 수

관련 문제