您提供的函数在上下文中没有主题。父元素之一需要使用 ThemeProvider

mrh*_*fat 7 javascript reactjs material-design material-ui

我正在项目中创建导航栏。在我的项目中我使用

  • mui/图标材料:^5.2.5
  • mui/材料:^5.2.6
  • mui/样式:^5.2.3
现在我的文件夹结构是
  • 根.jsx
    • 导航栏.jsx
    • 样式.js
我有一个错误
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.
Run Code Online (Sandbox Code Playgroud)
我尝试修复
  • 在 Root.jsx 添加 ThemeProvider
  • 从 Root.jsx 中删除并添加到 Navbar.jsx
  • & 其他的

注意:我不了解 Material UI。请帮助我摆脱这个错误。我在这里提供我的代码。

代码
  • 代码Root.jsx
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.
Run Code Online (Sandbox Code Playgroud)
  • 代码Navbar.jsx
import React from 'react'
import Navbar from './Navbar'

const Root = () => {
    return (
        <>
            <Navbar />
        </>
 )}
export default Root
Run Code Online (Sandbox Code Playgroud)
  • 代码style.js
import React from 'react'
import { AppBar, Menu, MenuItem, Toolbar, Typography, IconButton, Badge } from '@mui/material'
import { ShoppingCart } from '@mui/icons-material'
import useStyles from './styles'
import Logo from '../../images/logo.png'

const Navbar = () => {

    const classes = useStyles()

    return (
        <>
            <AppBar className={classes.appBar} position='fixed' color='inherit'>
                <Toolbar>
                    <Typography className={classes.title} variant='h6' color='inherit'>
                        <img className={classes.image} alt='Tech Cart' src={Logo} height='25px' />
                        Tech Cart
                    </Typography>
                    <div className={classes.grow} />
                    <div className={classes.button}>
                        <IconButton aria-label='Show cart products' color='inherit'>
                            <Badge badgeContent={2} color='secondary'>
                                <ShoppingCart />
                            </Badge>
                        </IconButton>
                    </div>
                </Toolbar>
            </AppBar>
        </>
    )
}
export default Navbar
Run Code Online (Sandbox Code Playgroud)

har*_*jog 5

我也遇到了这个问题。以下是我解决该问题所遵循的步骤:

  1. 在将使用 mui 的组件中添加以下导入: import

  2. 接下来,创建一个主题。 创建主题

  3. 将组件包装在 Themeprovider 中并将主题传递给它: themeprovider


小智 1

您需要使用 mui 中的 createTheme 函数,https://mui.com/customization/theming/在这里您可以观看示例。MakeStyles 用于设置特定组件的样式,而不是整个应用程序。

所以你需要做这样的事情:

const theme = createTheme({
  //here you set palette, typography ect...
})
Run Code Online (Sandbox Code Playgroud)

然后你将整个应用程序包装在 ThemeProvider 中,如下所示......

<ThemeProvider theme={theme}>
  //Your application
</ThemeProvider>
Run Code Online (Sandbox Code Playgroud)

然后,当您使用 makeStyles({theme}) 时,您的主题对象将具有您所描述的主题值。