【问题标题】:Why Material-UI is not recognizing the theme.spacing function?为什么 Material-UI 无法识别 theme.spacing 功能?
【发布时间】:2019-02-09 18:30:09
【问题描述】:
说明
我正在尝试在 React 应用程序中使用 Material-UI 的 theme.spacing 函数,但无法识别 spacing 函数。
Javascript 错误信息是:TypeError: theme.spacing is not a function
我不确定这是错误还是我正在安装的框架版本有问题。
上下文
根据 package-lock.json 文件,这些是正在安装的框架版本:
- 材料-UI:v3.9.2
- 反应:v16.8.1
- 铬:v72.0.3626.96
- TypeScript:无
- create-react-app: v3.2.2
【问题讨论】:
标签:
javascript
reactjs
material-ui
【解决方案2】:
试试这个。
import { makeStyles } from '@material-ui/core/styles'
const userStyles = makeStyles (theme => ({
gridAlign : {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.secondary,
},
})
【解决方案3】:
之前:import { makeStyles } from '@material-ui/core'; 可以工作。
但现在在最新的材质 UI 版本中,我们需要添加以下导入:
import { makeStyles } from '@material-ui/styles';
【解决方案4】:
对于材质 ui 版本 5.1.0
以下对我有用(正如@Worm所说)
import { makeStyles } from '@mui/styles';
记得安装@mui/styles
如果你收到类似的警告
MUI: The `styles` argument provided is invalid.
You are providing a function without a theme in the context.
One of the parent elements needs to use a ThemeProvider.
MUI: The `styles` argument provided is invalid.
You are providing a function without a theme in the context.
One of the parent elements needs to use a ThemeProvider.
用 ThemeProvider 包裹父容器
export default ParentComponentName = (props)=>{
return(
<ThemeProvider theme={theme}>
<SomeThemeComponent>
<SomeComponent />
</SomeThemeComponent>
<ThemeProvider>
)
}
参考
https://mui.com/styles/api/#examples-4
PS:由于信用限制,我无法发表评论,因此发布为新答案。
【解决方案5】:
尝试将@material-ui/core 包升级到最低版本 4.0.0。
运行 npm i @material-ui/core@4.0.0
它解决了我的问题。
【解决方案6】:
接下来就做吧:
const theme = createMuiTheme({
status: {
danger: orange[500],
},
});
export default function CustomStyles() {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox />
</ThemeProvider>
);
}
【解决方案7】:
添加导入使错误消失:
import {makeStyles} from "@material-ui/**core**/styles";