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

相关推荐
IT_陈寒16 小时前
React 性能优化必杀技:这5个Hook组合让你的应用提速50%!
前端·人工智能·后端
再吃一根胡萝卜16 小时前
Git 强制推送指南:新手必读的「危险操作」解析
前端
诚实可靠王大锤17 小时前
react-native项目通过华为OBS预签名url实现前端直传
前端·react native·华为
Monly2117 小时前
Vue:下拉框多选影响行高
前端·javascript·vue.js
是罐装可乐17 小时前
前端架构知识体系:Source Map 的用法和全面解析
前端·映射·前端架构·代码安全·源码地图·source-map
小桥风满袖17 小时前
极简三分钟ES6 - ES8中对象扩展
前端·javascript
代码的余温17 小时前
Web服务器VS应用服务器:核心差异解析
运维·服务器·前端
一涯17 小时前
日常小常识记录
前端
那一抹阳光多灿烂17 小时前
CSS 编码规范
前端·css
degree52017 小时前
CSS :has() 选择器详解:为什么它是“父选择器”?如何实现真正的容器查询?
前端·css·css3