2016-04-14 60 views
1

这是我MainLayout组件:哪些React组件应该与参数一起使用?

export const MainLayout = ({header, content, footer}) =>(
<div> 
    <header> 
     {header} 
    </header> 
    <main> 
     <Paper style={contentStyle} zDepth={1}> 
      {content} 
     </Paper> 
    </main> 
    <footer> 
     <Paper style={contentStyle}> 
      {footer} 
     </Paper> 
    </footer> 
</div>); 

这是我与React.Component

export class MainLayout extends React.Component{ 
constructor({header, content, footer}){ 
    super(); 
    this.header = header; 
    this.content = content; 
    this.footer = footer; 
} 
render(){ 
    return(
     <div> 
      <header> 
       {this.header} 
      </header> 
      <main> 
       <Paper style={contentStyle} zDepth={1}> 
        {this.content} 
       </Paper> 
      </main> 
      <footer> 
       <Paper style={contentStyle}> 
        {this.footer} 
       </Paper> 
      </footer> 
     </div> 
    ) 
}} 

当我使用我的第一个MainLayout组件的所有标题,内容MainLayout和页脚正常工作。我想添加构造函数()componentDidMount()但我不能!所以,我试图使用ES6类(我的第二个MainLayout的React.Component)与construcor()我添加3个参数。这对我有用! 但是,当我链接到其他页面时,内容不响应。我的意思是旧的内容仍然是一样的。 Unitl我刷新页面,然后内容被更改!

那么你能告诉我,如果我在创建这些组件时犯了错误吗? 非常感谢你们的援助:d

回答

2

Stateless componentsconst mainLayout =() => {})只是功能,所以他们缺乏构造函数和生命周期方法。

当您使用ES6 class component时,所有属性都附加到this.props。您不必手动将它们添加到this。每当道具改变时,反应将重新渲染组件。

export class MainLayout extends React.Component{ 
constructor(props){ // not strictly needed, but since you want a constructor anyway... 
    super(props); 
} 
render(){ 
    return(
     <div> 
      <header> 
       {this.props.header} // all props are bound to this.props 
      </header> 
      <main> 
       <Paper style={contentStyle} zDepth={1}> 
        {this.props.content} // all props are bound to this.props 
       </Paper> 
      </main> 
      <footer> 
       <Paper style={contentStyle}> 
        {this.props.footer} // all props are bound to this.props 
       </Paper> 
      </footer> 
     </div> 
    ) 
}} 

如果你不想提及this.props所有的时间,你可以用解构,就像你在无状态组件所做的:

export class MainLayout extends React.Component{ 
constructor(props){ // not strictly needed, but since you want a constructor anyway... 
    super(props); 
} 
render(){ 
    const { header, content, footer } = this.props; // destructure this.props to consts 

    return(
     <div> 
      <header> 
       {header} 
      </header> 
      <main> 
       <Paper style={contentStyle} zDepth={1}> 
        {content} 
       </Paper> 
      </main> 
      <footer> 
       <Paper style={contentStyle}> 
        {footer} 
       </Paper> 
      </footer> 
     </div> 
    ) 
}} 

顺便说一句 - 在哪里呢contentStyle从何而来?

+0

我将纸张样式添加到内容:D 非常感谢!这真的帮助我! –

+0

欢迎。 “contentStyle”不应该成为道具之一吗? –

+0

是的!现在我遇到了问题。当屏幕响应时(大,中,小),我希望contentStyle自动更改。或者你想让我把contentStyle放入构造函数中?我很抱歉,如果我不明白你的观点:D –

相关问题