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

相关推荐
铅笔侠_小龙虾2 分钟前
深入理解 Vue.js 原理
前端·javascript·vue.js
西西学代码5 分钟前
Flutter---showCupertinoDialog
java·前端·flutter
你的眼睛會笑8 分钟前
vue3 使用html2canvas实现网页截图并下载功能 以及问题处理
前端·javascript·vue.js
ZTLJQ19 分钟前
植物大战僵尸HTML5游戏完整实现教程
前端·游戏·html5
无光末阳35 分钟前
vue 环境下多个定时器的创建与暂停的统一封装
前端·vue.js
Hilaku37 分钟前
技术Leader的“第一性原理”:我是如何做技术决策的?
前端·javascript·面试
liyf38 分钟前
发布-订阅(Publish–Subscribe) vs 观察者模式(Observer Pattern)
前端
云中雾丽44 分钟前
Flutter 里的 Riverpod 用法解析
前端
前端snow1 小时前
记录:非常典型的一个redux问题
前端
慧一居士1 小时前
src/App.vue 和 public/index.html 关系和区别
前端·vue.js