我应该将哪些React组件用于参数?

时间:2016-04-14 11:37:06

标签: reactjs material-ui

  

这是我的MainLayout组件:

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>);
  

这是我的MainLayout和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组件时,所有标题,内容和页脚都正常工作。我想添加构造函数() componentDidMount(),但我不能!所以,我正在尝试使用ES6类(我的第二个MainLayout的React.Component)与 construcor()我添加3个参数。这对我有用! 但是,当我链接到其他网页时,内容没有响应。我的意思是旧内容仍然相同。我刷新页面然后更改内容!

  

那么你能否告诉我是否在创建这些组件时犯了错误?   非常感谢你的帮助:D

1 个答案:

答案 0 :(得分: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>
    )
}}

btw - contentStyle来自哪里?

相关问题