You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React JS计数器应用中添加Material Box组件?

在React计数器应用中集成Material UI Box组件

步骤1:安装Material UI核心依赖

先在项目根目录执行命令,安装Material UI的必要依赖:

npm install @mui/material @emotion/react @emotion/styled

步骤2:修改App.js代码

你可以用Material UI的Box组件重构现有布局,同时保留计数器的核心功能。下面是调整后的完整代码:

import React, { useState } from "react";
import { Button } from 'react-bootstrap';
import Box from '@mui/material/Box';

function App() {
  const [count, setCount] = useState(0);

  return (
    <Box 
      sx={{ 
        maxWidth: '600px', 
        margin: '3rem auto', 
        padding: '2rem',
        borderRadius: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}
    >
      <Box textAlign="center" mb={4}>
        <h1>Counter App</h1>
      </Box>
      <Box textAlign="center" mb={5}>
        <h2 style={{ margin: '2rem 0' }}>{count}</h2>
        <Box display="flex" justifyContent="flex-end" gap={2}>
          <button
            className="rounded-circle btn btn-success"
            onClick={() => setCount(count + 1)}
          >+</button>
          <button
            className="rounded-circle btn btn-success"
            onClick={() => setCount(count - 1)}
            disabled={count === 0}
          >-</button>
          <Button 
            type="reset"
            onClick={() => setCount(0)}
            disabled={count === 0}
          >Reset</Button>
        </Box>
      </Box>
    </Box>
  );
}

export default App;

关键说明

  • 用Box组件替代了原有的Bootstrap容器类,通过sx属性设置Material UI的内联样式,比如外边距、阴影、圆角等,实现更灵活的布局控制。
  • 保留了你原本使用的Bootstrap按钮样式,若想完全切换到Material UI按钮,可将react-bootstrap的Button替换为@mui/material/Button。
  • sx属性是Material UI专属的样式方案,支持响应式设计和主题变量,可根据需求调整样式参数。

内容的提问来源于stack exchange,提问作者Abinash ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:05:24