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

相关推荐
索迪迈科技几秒前
网络请求库——Axios库深度解析
前端·网络·vue.js·北京百思可瑞教育·百思可瑞教育
gnip8 分钟前
JavaScript二叉树相关概念
前端
一朵梨花压海棠go1 小时前
html+js实现表格本地筛选
开发语言·javascript·html·ecmascript
attitude.x1 小时前
PyTorch 动态图的灵活性与实用技巧
前端·人工智能·深度学习
β添砖java1 小时前
CSS3核心技术
前端·css·css3
空山新雨(大队长)1 小时前
HTML第八课:HTML4和HTML5的区别
前端·html·html5
猫头虎-前端技术2 小时前
浏览器兼容性问题全解:CSS 前缀、Grid/Flex 布局兼容方案与跨浏览器调试技巧
前端·css·node.js·bootstrap·ecmascript·css3·媒体
阿珊和她的猫2 小时前
探索 CSS 过渡:打造流畅网页交互体验
前端·css
元亓亓亓2 小时前
JavaWeb--day1--HTML&CSS
前端·css·html