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

相关推荐
英俊潇洒美少年7 小时前
Vue 生产环境打包:SourceMap、压缩、混淆、加密全解 + 最佳实践
前端·javascript·vue.js
巴博尔7 小时前
UNIAPP中NVUE页面 动画
android·前端·javascript·ios·uni-app
猫头虎-前端技术8 小时前
JS 作用域与闭包:从变量提升到闭包陷阱的超详细解析
开发语言·javascript·云计算·bootstrap·ecmascript·openstack·perl
她说人狗殊途9 小时前
基于 vue-cli 创建
前端·javascript·vue.js
AZaLEan__10 小时前
前端移动端适配与 Bootstrap
前端·bootstrap·html
大家的林语冰10 小时前
Deno 2.8 正式发布,再次超越 Bun,史上最大的次版本升级诞生!
前端·javascript·node.js
渣渣xiong10 小时前
从零开始:前端转型AI agent直到就业第五十七天-第五十八天
前端·人工智能·python
影寂ldy10 小时前
C#数组的属性和方法(Clear / Copy / IndexOf )
开发语言·javascript·c#
Brave & Real11 小时前
小程序 const 在js中以及与同类的var和let之间的差异
javascript·微信小程序·小程序
AI周红伟11 小时前
周红伟:长鑫科技(CXMT)财务全景分析
前端·chrome·科技