【问题标题】:How to create a Layout with React如何使用 React 创建布局
【发布时间】:2021-10-23 11:23:15
【问题描述】:
// components/Layout/Layout.tsx
const Layout = () => {
  return (
    <div>

    </div>
  )
}

export default Layout

// components/Layout/Header/Header.tsx
const Header = () => {
  return (
    <header>
      <h2>This is Header</h2>
    </header>
  )
}

export default Header

// components/Layout/Footer/Footer.tsx
const Footer = () => {
  return (
    <footer>
      <h2>This is Footer</h2>
    </footer>
  )
}

export default Footer

// pages/index.tsx
import Layout from "../components/Layout/Layout"
import HomeContainer from "../containers/Home/HomeContainer"

const HomePage = () => {
  return (
    <Layout>
      <HomeContainer />
    </Layout>
  )
}

export default HomePage

我正在使用 React 制作一个简单的网页。这一次,我试图在编写时考虑到 HTML 结构,但我有一个难题。

如何通过创建布局组件并用路由包裹它来实现页面渲染时不应该有其他页眉或页脚的页面?

※补充问题:是否可以在Layout组件中使用useMediaQuery创建移动响应式网页?

【问题讨论】:

    标签: html reactjs layout header


    【解决方案1】:

    你需要在 Layout 组件中渲染 children 属性。

    const Layout = (props) => {
      return (
        <div>
          <header>Header</header>
          { props.children }
          <footer>Footer</footer>
        </div>
      )
    }
    

    【讨论】:

      【解决方案2】:

      您需要在div 内渲染子级。 Layout 组件语法如下:

      // components/Layout/Layout.tsx
      const Layout = ({children}) => {
        return (
          <div>
            {children}
          </div>
        )
      }
      
      export default Layout;
      

      使用布局组件

      const AnyPage = () => {
        return (
          <Layout>
            \* Children written here will render inside your div of Layout component *\
          </Layout>
        )
      }
      
      export default AnyPage;
      

      带有页眉和页脚的主页会是这样的

      // pages/index.tsx
      import Layout from "../components/Layout/Layout"
      //import Header and Footer here
      
      const HomePage = () => {
        return (
          <Layout>
            <Header />
            {Additional components or HTML code here}
            <Footer />
          </Layout>
        )
      }
      
      export default HomePage;
      

      ※附加:是的,您可以为Layout 组件的div 添加一个CSS 类,使其具有响应性。

      // components/Layout/Layout.tsx
      
      //import style sheet here
      
      const Layout = ({children}) => {
        return (
          <div className="class-to-make-responsive">
            {children}
          </div>
        )
      }
      
      export default Layout;
      

      【讨论】:

        猜你喜欢
        • 2018-05-30
        • 1970-01-01
        • 1970-01-01
        • 2021-05-31
        • 2021-07-30
        • 2020-01-21
        • 2012-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多