gpt4 book ai didi

reactjs - 如何在没有 ThemeProvider 的情况下使用 MUI v5 makeStyles?

转载 作者:行者123 更新时间:2023-12-02 01:55:18 25 4
gpt4 key购买 nike

我有一个 styles.tsx 文件,因为我不想将样式放入我的组件中:

//styles.tsx

import {grey, purple} from '@mui/material/colors';
import {styled, Theme} from '@mui/material/styles';
import {createStyles, makeStyles} from '@mui/styles';

export const drawerStyles = makeStyles((theme: Theme) =>
createStyles({
logo: {
'fontSize': '2em',
'fontFamily': 'Oleo Script Swash Caps',
'background': 'transparent',
'border': 'none',
'marginLeft': theme.spacing(1),
'width': '41px',
'overflow': 'hidden',
'transition': 'all 0.1s ease-out',
'cursor': 'pointer',
'&:hover': {
color: purple[700],
},
},
slide: {
paddingLeft: '8px',
width: '100%',
},
}),
);

在另一个组件中,我导入drawerStyles:

// drawerContainer.tsx

import {drawerStyles} from 'Src/styles';

export const DrawerContainer = () => {
const classes = drawerStyles();

return (
<Box className={`${classes.logo}>
<p>some text</p>
</Box>
)

代码可以编译,但浏览器返回错误:

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.

在我的 index.tsx 上,我使用 ThemeProvider:

// index.tsx

import {ThemeProvider, StyledEngineProvider} from '@mui/material/styles';
import {theme} from 'Src/theme';

const Root = () => {
return (
<ApolloProvider client={client}>
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
<CssBaseline>
<App />
</CssBaseline>
</ThemeProvider>
</StyledEngineProvider>
</ApolloProvider>
);
};

render(<Root />, document.getElementById('root'));

我认为问题是因为 styles.tsx 不在 index.tsx 范围内。因此,当浏览器加载文件时,它没有 themeprovider 上下文。

我应该移动组件中的所有样式吗?或者还有其他办法吗?

//编辑//

使用 styled api 创建样式:

// styles.tsx

export const Logo = styled(Box)(({theme}) => ({
'fontSize': '2em',
'fontFamily': 'Oleo Script Swash Caps',
'background': 'transparent',
'border': 'none',
'marginLeft': theme.spacing(1),
'width': '41px',
'overflow': 'hidden',
'transition': 'all 0.1s ease-out',
'cursor': 'pointer',
'&:hover': {
color: purple[700],
},
}));
// DrawerContainer.tsx

<Link data-cy='btn_home' to='/'>
<Logo component='button'>Movieseat</Logo>
</Link>

我有点不喜欢这种语法,不清楚 Logo 是什么类型的对象。

最佳答案

参见this回答更多细节。简而言之,makesStyles/withStyles 不再是 MUI v5 中的第一类 API,并且计划在 v6 中删除。如果您使用旧的API,则必须自己添加主题。

在 v4 中,您可以 import makeStyles来自 @material-ui/core/styles ,无需提供自定义主题。您可以在 v5 中执行相同的操作,但只能 with the new styled API所有 MUI 组件都在内部使用它。

关于reactjs - 如何在没有 ThemeProvider 的情况下使用 MUI v5 makeStyles?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69678265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com