2017-10-05 54 views
2

我在寫ReactJS一個容器組件和我傳遞一個道具該組件將被渲染爲「主」的內容,就像這樣:陣營JS - 道具通過嵌套組件

class RegistrationContainer extends Component { 

    render() { 
     const MainContent = this.props.mainContent; 

     return (
      <Row> 
       <Col offset="lg-3" lg={6}> 
        <MainContent /> 
       </Col> 
      </Row> 
     ); 
    } 

} 

export default RegistrationContainer; 

而且我passsing給它一個mainContent道具,像這樣:

import RegistrationContainer from './RegistrationContainer'; 
import RegistrationEntryView from './RegistrationEntryView'; 

class RegistrationCodeEntry extends Component { 

    render() { 
     return (
      <RegistrationContainer mainContent={RegistrationEntryView} /> 
     ); 
    } 
} 

export default RegistrationCodeEntry; 

我的問題是,我想RegistrationEntryView有道具,但似乎無法弄清楚如何定義/傳中它道具。如果我這樣做,我得到一個錯誤:

class RegistrationCodeEntry extends Component { 

    render() { 
     const RegistrationView = <RegistrationEntryView someProp="blah" /> ; 
     return (
      <RegistrationContainer mainContent={RegistrationView} /> 
     ); 
    } 
} 

export default RegistrationCodeEntry; 

錯誤如下:

invariant.js?7313:42 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of RegistrationContainer .

這是一些this.props.children能解決?我一直在努力讓自己的頭腦圍繞這個概念,所以任何有關我出錯的建議都將不勝感激。

+0

我覺得'this.props.children'可以解決你的問題。在RegistrationCodeEntry的'render()'方法中返回somethng:'return( );' – samAlvin

+0

謝謝,這正是我之後。 – deanmau5

回答

2

你可以這樣

class RegistrationCodeEntry extends Component { 

    render() { 
    return (
     <RegistrationContainer> 
      // Render it as children 
      <RegistrationEntryView someProp="blah" /> 
     </RegistrationContainer> 
    ); 
    } 
} 

this.props.children解決這個問題,然後在你的容器

class RegistrationContainer extends Component { 

    render() { 

    const MainContent = this.props.mainContent; 

    return (
    <Row> 
     <Col offset="lg-3" lg={6}> 
     // Render the passed children 
     {this.props.children} 
     </Col> 
    </Row> 
); 
} 
} 
+1

謝謝,這正是我之後的事情。 – deanmau5

1

你的做法是正確的。你只是去錯在這裏:

<Row> 
    <Col offset="lg-3" lg={6}> 
    <MainContent /> 
    </Col> 
</Row> 

而是做到這一點:

<Row> 
    <Col offset="lg-3" lg={6}> 
    { MainContent } 
    </Col> 
</Row> 

我個人認爲,這種方法比使用兒童更好。

當你這樣做 - const RegistrationView = <RegistrationEntryView someProp="blah" /> ;該組件已被渲染並轉換爲適當的格式。因此,您不能用<MainContent />重新渲染它。 所以在這種情況下使用{}是正確的。

祝你好運!