React | Center 组件

在 Flutter 中有 Center 组件,效果就是让子组件整体居中,挺好用。

React 中虽然没有对应的组件,但是可以简单封装一个:

  • index.less
css 复制代码
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  align-content: center;
  height: 100%;
}
  • index.tsx
ts 复制代码
import styles from './index.less';

interface CenterProps {
  children: React.ReactNode;
}

const Center: React.FC<CenterProps> = ({ children }) => {
  return <div className={styles.container}>{children}</div>;
};

export default Center;

使用:

ts 复制代码
import Center from './Center';

const CenterPage = () => {
  return (
    <div>
      good
      <div style={{ height: '200px', backgroundColor: 'green' }}>
        <Center>
          <div style={{ backgroundColor: 'orange' }}>
            <div
              style={{ backgroundColor: 'red', height: '50px', width: '100px' }}
            >
              古德古德
            </div>
            <div
              style={{ backgroundColor: 'blue', height: '50px', width: '60px' }}
            >
              古德2
            </div>
          </div>
        </Center>
      </div>
    </div>
  );
};

export default CenterPage;

效果:


补充:

Ant Design 的 Flex 组件也可以轻松让子组件居中,不过 5.10.0 版本才开始提供该组件:

https://ant-design.antgroup.com/components/flex-cn

相关推荐
一 乐13 小时前
宠物猫店管理|宠物店管理|基于Java+vue的宠物猫店管理管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·后端·宠物管理
熊猫比分管理员13 小时前
【全栈源码解决方案】Vue+Java四端齐全,一周交付可运行项目!
java·前端·vue.js
o***741714 小时前
【Nginx 】Nginx 部署前端 vue 项目
前端·vue.js·nginx
坚持就完事了14 小时前
CSS-5:盒子模型
前端·css·html
一 乐14 小时前
考公|考务考试|基于SprinBoot+vue的考公在线考试系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·课程设计
吃饺子不吃馅14 小时前
优化:如何避免 React Context 引起的全局挂载节点树重新渲染
前端·面试·github
q***721914 小时前
Y20030018基于Java+Springboot+mysql+jsp+layui的家政服务系统的设计与实现 源代码 文档
android·前端·后端
林太白14 小时前
跟着TRAE SOLO全链路看看项目部署服务器全流程吧
前端·javascript·后端
特级业务专家14 小时前
把 16MB 中文字体压到 400KB:我写了一个 Vite 字体子集插件
javascript·vue.js·vite
humor14 小时前
Quill 2.x 从 0 到 1 实战 - 为 AI+Quill 深度结合铺路
前端·vue.js