react - 4. Layout

114 阅读1分钟

src 目录下创建一个名为 layout 的文件夹,直接将 antd 官方的上中下布局复制使用。

// src/layout/index.tsx
import * as React from 'react'
import { Layout as AntdLayout, Breadcrumb, Menu, theme } from 'antd'interface LayoutProps {
  children: React.ReactNode
}
​
const { Header, Content, Footer } = AntdLayoutconst items = new Array(15).fill(null).map((_, index) => ({
  key: index + 1,
  label: `nav ${index + 1}`,
}))
​
const Layout: React.FunctionComponent<LayoutProps> = ({ children }) => {
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken()
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
      <AntdLayout>
        <Header style={{ display: 'flex', alignItems: 'center' }}>
          <div className="demo-logo" />
          <Menu
            theme="dark"
            mode="horizontal"
            defaultSelectedKeys={['2']}
            items={items}
            style={{ flex: 1, minWidth: 0 }}
          />
        </Header>
        <Content style={{ padding: '0 48px' }}>
          <Breadcrumb style={{ margin: '16px 0' }}>
            <Breadcrumb.Item>Home</Breadcrumb.Item>
            <Breadcrumb.Item>List</Breadcrumb.Item>
            <Breadcrumb.Item>App</Breadcrumb.Item>
          </Breadcrumb>
          <div
            style={{
              background: colorBgContainer,
              minHeight: 280,
              padding: 24,
              borderRadius: borderRadiusLG,
            }}
          >
            {children}
          </div>
        </Content>
        <Footer style={{ textAlign: 'center' }}>
          Ant Design ©{new Date().getFullYear()} Created by Ant UED
        </Footer>
      </AntdLayout>
    </div>
  )
}
​
export default Layout

然后,在你的 App 组件中使用这个布局组件:

// src/App.tsx
import * as React from 'react'
import Home from './pages/home'
import Layout from './layout'const App: React.FC = () => {
  return (
    <Layout>
      <Home />
    </Layout>
  )
}
​
export default App

image-20240618223419590.png

Layout 组件实现了一个简单的上中下布局,其中 header 用于显示页眉内容,main 用于显示主要内容区域,footer 用于显示页脚内容。