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

相关推荐
风语者日志1 天前
[LitCTF 2023]作业管理系统
前端·网络·安全·web安全·ctf
excel1 天前
深入解析:Vue 编译器核心工具函数源码(compiler-core/utils.ts)
前端
excel1 天前
第五章:辅助函数与全流程整合
前端
excel1 天前
🔍 深度解析:Vue 编译器中的 validateBrowserExpression 表达式校验机制
前端
excel1 天前
深度解析:Vue 模板编译器中的 Tokenizer 实现原理
前端
excel1 天前
🧩 Vue 编译核心:transform.ts 源码深度剖析
前端
excel1 天前
Vue Runtime Helper 常量与注册机制源码解析
前端
excel1 天前
Vue 模板编译器核心选项解析:从 Parser 到 Codegen 的全链路设计
前端
excel1 天前
第四章:表达式与循环解析函数详解
前端
excel1 天前
第三章:指令与属性解析函数组详解
前端