2017-04-13 48 views

回答

2

內容

<SomethingElse /> 
<YetAnother> 
    <SomeMore /> 
</YetAnother> 

將成爲<About />一個特殊的道具,叫children

結構將被遞歸調用,編譯JSX爲數React.createElement(component, props, ...children)

但要注意,反應贏得」 t如果您的About組件僅包含

class Abount extends React.Component { 
    render() { 
    return <h1>About</h1> 
    } 
} 

,並不會呈現this.props.children的話,那麼

<SomethingElse /> 
<YetAnother> 
    <SomeMore /> 
</YetAnother> 

將完全忽略。

所以,如果你想支持你的組件嵌套組件,您需要自己處理props.children

最簡單的方法是寫在你的渲染功能{this.props.children},例如:

class About extends React.Component { 
    render() { 
    return (
     <div> 
     <h1>About</h1> 
     {this.props.children} 
     </div> 
    ) 
    } 
} 
+0

奈斯利解釋:)我想有很多人用魔法假設子組件工作的反應,而不是僅僅是另一個支柱。 –

+0

順便說一句,似乎這樣'About'有一堆孩子,就像一個HTML標記' ...'有很多孩子。因此,在HTML格式中,它就像「將所有內容都包含在body內」,但是如果您繪製HTML樹,則它是一個「body」元素節點,然後是一羣子節點,它們是該節點的子節點 –

0

考慮follwoing代碼

<About> 
    <SomethingElse /> 
    <YetAnother> 
    <SomeMore /> 
    </YetAnother> 
</About> 

在這裏你有嵌套的組件。因此SomethingElse, YetAnotherAbout組件內呈現爲兒童。如果您看到About組件的渲染代碼,您會發現類似{this.props.children}的東西,這基本上意味着current組件的子組件將在此處呈現。

類似的是YetAnother具有SomeMore作爲子組件的情況。

我希望我能解釋它。

+0

看來你必須明確使用'{this'這一行。props.children}''在你的'About'組件的代碼中渲染孩子?如果你不包括那一行,那麼根本沒有孩子會被顯示出來? –

+0

是的,如果你不包含'this.props.children'這一行,那麼沒有孩子會被渲染 –