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

相关推荐
战南诚5 分钟前
VUE中,keep-alive组件与钩子函数的生命周期
前端·vue.js
发现一只大呆瓜7 分钟前
React-彻底搞懂 Redux:从单向数据流到 useReducer 的终极抉择
前端·react.js·面试
霍理迪31 分钟前
Vue的响应式和生命周期
前端·javascript·vue.js
李剑一35 分钟前
别再瞎写了!Cesium 模型 360° 环绕,4 套源码全公开,项目直接用
前端
小码哥_常1 小时前
Android消息机制:Handler、Looper和Message的深度剖析
前端
小码哥_常1 小时前
安卓开发新姿势:文件Picker全攻略,无痛适配不再难
前端
happymaker06261 小时前
web前端学习日记——DAY04
前端·学习
发现一只大呆瓜1 小时前
React-路由监听 / 跳转 / 守卫全攻略(附实战代码)
前端·react.js·面试
swipe2 小时前
为什么 RAG 一定离不开向量检索:从文档向量化到语义搜索的工程实现
前端·llm·agent
OpenTiny社区2 小时前
AI-Extension:让 AI 真的「看得到、动得了」你的浏览器
前端·ai编程·mcp