2016-12-04 177 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