2016-12-04 102 views
0

我在我的应用程序使用react-router,它看起来是这样的:获取组件儿童型阵营

<Router history={hashHistory}> 
    <Route path="/" component={Root}> 
     <Route path="about" component={Child1} /> 
     <Route path="about" component={Child2} /> 
     // and so on... 
    </Route> 
</Router> 

我想知道这是传下来的每一次Root孩子的类型有一个变化。事情是这样的:

if(typeof this.props.children === Child1) { 
    // do stuff 
} 

回答

1

的孩子可能是不同类型的,所以如果可能有多个孩子,你需要检查this.props.children[0]和这样的,不是children作为一个整体。 (如下面的评论指出:props.children显然是独生子女,如果有一个孩子,否则,这是孩子们的阵列状列表。)

我不知道,如果它的记录,但在children条目似乎有一个type属性指的是构造函数的元素:

class Child1 extends React.Component { 
 
    render() { 
 
    return <div>Child1</div>; 
 
    } 
 
} 
 
class Child2 extends React.Component { 
 
    render() { 
 
    return <div>Child2</div>; 
 
    } 
 
} 
 
const Main = props => { 
 
    const children = "length" in props.children 
 
    ? Array.from(props.children) 
 
    : [props.children]; 
 
    console.log(`Children in '${props.title}':`); 
 
    children.forEach((child, index) => { 
 
    console.log(`* ${index}: ${child.type.name}`); 
 
    }); 
 
    return (
 
    <div style={{paddingLeft: "6px"}}> 
 
     {props.title} 
 
     <div> 
 
     {props.children} 
 
     </div> 
 
    </div> 
 
); 
 
}; 
 

 
ReactDOM.render(
 
    <div> 
 
    <Main title="Two children"> 
 
     <Child1 /> 
 
     <Child2 /> 
 
    </Main> 
 
    <Main title="One child of type 1"> 
 
     <Child1 /> 
 
    </Main> 
 
    <Main title="One child of type 2"> 
 
     <Child2 /> 
 
    </Main> 
 
    </div>, 
 
    document.getElementById("react") 
 
);
<div id="react"></div> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

+0

如果组件只包含一个孩子,'this.props.children'返回上而不是单个元素的数组。 – cynicaldevil

+0

@cynicaldevil:**哇**,我不知道。太疯狂了。无论如何,希望我在编辑中提到的“类型”是有帮助的。 –

+0

是的,它的工作!谢谢! – cynicaldevil