布局组件

在我们的应用程序中,我们将在各种页面中使用通用的样式。 为此,我们可以创建一个通用的布局组件,并为每个页面使用它。 以下是一个例子:

将此内容添加到components/MyLayout.js中:

  1. import Header from './Header'
  2. const layoutStyle = {
  3. margin: 20,
  4. padding: 20,
  5. border: '1px solid #DDD'
  6. }
  7. const Layout = (props) => (
  8. <div style={layoutStyle}>
  9. <Header />
  10. {props.children}
  11. </div>
  12. )
  13. export default Layout

一旦我们这样做,我们可以在我们的页面中使用这个布局如下:

  1. // pages/index.js
  2. import Layout from '../components/MyLayout.js'
  3. export default () => (
  4. <Layout>
  5. <p>Hello Next.js</p>
  6. </Layout>
  7. )
  8. // pages/about.js
  9. import Layout from '../components/MyLayout.js'
  10. export default () => (
  11. <Layout>
  12. <p>This is the about page</p>
  13. </Layout>
  14. )

Remember, you can access the app at http://localhost:3000/ to see what it looks like.

Now let’s try removing {props.children} from the Layout and see what happens to the app.

What will happen to the app?

  1. There will be no effect.
  2. The content of the page being displayed will be removed.
  3. It will throw an error saying: Layout needs some content.”
  4. It will log a warning message for the browser component.

请记住,您可以访问 http://localhost:3000/ 来查看它的外观。

现在我们来试试从“布局”中删除{props.children},看看会发生什么?

  1. ✦不会有影响。
  2. ✓显示页面的内容将被删除。
  3. ✦会出现一个错误:“布局需要一些内容”。
  4. ✦它将记录浏览器组件的警告消息。