反应将子组件放置在父组件中

时间:2020-04-07 20:37:03

标签: reactjs

关于ReactJS,我是一个新手。我试图创建一个页面组件,它具有一个导航组件和里面的其他一些div。但是我希望页面组件成为页面内容的父代。

它看起来像这样:

<Page>
    <h1>Hello World</h1>
    <p>This is the page content</p>
    <DummyChildComponent />
    ...
</Page>

我知道我可以传递页面内容作为道具,但这感觉不对。

是否可以在父组件之间传递页面内容?

非常感谢!

3 个答案:

答案 0 :(得分:1)

将内容作为道具传递绝对没有错!不仅很好,甚至还有一个专门用于此目的的children专用道具,完全可以满足您的需求。

如果您希望<Page>成为功能组件,您可以这样做:

const Page = (props) => {
    return (
        <div className="myFancyClass">
            <h1>A fancy header that will be visible on every page</h1>
            {props.children}
            <p>Some extra information underneath my pretty page!</p>
        </div>
    )
}

如果您希望<Page>成为类组件,您可以这样做:

class Page extends React.Component {
    render() {
        return (
            <div className="myFancyClass">
                <h1>A fancy header that will be visible on every page</h1>
                {this.props.children}
                <p>Some extra information underneath my pretty page!</p>
            </div>
        )
    }
}

这在您提供的示例中应该可以很好地工作

希望这会有所帮助!

答案 1 :(得分:0)

我知道我可以传递页面内容作为道具,但这感觉不对。

最常见的解决方案是使用props.children属性,它是这样传递的内容:<Tag>{content}</Tag>

const Layout = ({children}) => {
  return (
    <>
      <Navbar />
      {children}
      <Footer />
    </>
  )
}

然后,您可以在页面组件中像这样使用它:

const ExamplePage = () => {
 return (<Layout>
    <h2>Page content</h2>
    <p>Example content</p>
  </Layout>)
}

Gatsby默认使用该方法。

答案 2 :(得分:-1)

例如,您可以使用CSS-in-JS来做到这一点:

  • 利纳里亚
  • astroturf
  • 样式化的组件

在每个库中,语法将大致相同:

import React from 'react';
import styled from 'styled-components';

export const UnstyledPage = ({ className }) => 
  (
    <div className={className}>
      // Here is your content components
    </div>
  )

const Page = styled(UnstyledPage)`
  // Here is styles for your parent Page component
`;

或:

import React from 'react';
import styled from 'styled-components';

export const Page = ({}) => 
  (
    <PageWrap>
      // Here is your content components
    </PageWrap>
  )

const PageWrap = styled.div`
  // Here is styles for your parent Page component
`;

或以下带有children道具的任何示例:

import React from 'react';
import styled from 'styled-components';

export const Page = ({ children }) => 
  (
    <PageWrap>
      { children }
    </PageWrap>
  )

const PageWrap = styled.div`
  // Here is styles for your parent Page component
`;