gpt4 book ai didi

javascript - 在 Next JS 中,Material UI makeStyles 在刷新时撤消自定义 css

转载 作者:行者123 更新时间:2023-12-04 02:28:01 24 4
gpt4 key购买 nike

我正在开发一个 NextJS 站点,该站点具有一些通过 MaterialUI 的 makeStyles 应用的自定义样式。它在第一次加载时工作正常,然后在第二次撤消所有自定义工作。似乎它与路由有关,因为它唯一起作用的时间是当我第一次被定向到页面本身时。它发生在 2 个不同的页面上,其中一个是通过 href='/login' 引导的。另一个是通过 next/router router.push('/register') 引导的
我假设这与 Next 加载页面的方式有关?但我会说这两个都是prerendered pages根据右下角的图标。

import React, {useState} from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { login } from '../store/user/action'
import { useRouter } from 'next/router'

import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';

const style = makeStyles({
root: {
marginBottom: '20px',
textAlign: 'center'
},
});


function Signin({login}) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

const router = useRouter();

const clickRegister = (e) => {
e.preventDefault();
router.push('/register')
}

const classStyle = style();

return (
<div className='flex flex-column center m-20 w-750'>
<h3 className='m-20'>Login</h3>
<form className='flex flex-column w-750 center' onSubmit={e=>login(e, {email, password})} >
<TextField
className={classStyle.root}
required
type='email'
id="email"
label="Email"
variant="outlined"
onChange={e=>setEmail(e.target.value)}
/>
<TextField
className={classStyle.root}
required
type='password'
id="password"
label="Password"
variant="outlined"
onChange={e=>setPassword(e.target.value)}
/>

<input
type='submit'
className='purple-button mt-20 h-3'
onClick={e=>login(e)}
value='Login' />
</form>
<p>Don't Have an account?</p>
<form onSubmit='/register'>
<input value='Register' type='submit' className='flex flex-column w-750 center purple-button h-3' onClick={e=>clickRegister(e)} />
</form>

</div>
)
}



const mapStateToProps = (state) => ({
email: state.user.email,
token: state.user.token,
isLoggedIn: state.user.isLoggedIn,
})

const mapDispatchToProps = (dispatch) => {
return {
login: bindActionCreators(login, dispatch),
}
}

export default connect(mapStateToProps, mapDispatchToProps)(Signin)
"dependencies": {
"@material-ui/core": "4.11.3",
"axios": "0.21.1",
"material-ui": "0.20.2",
"next": "9.4.1",
"next-redux-wrapper": "^6.0.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-redux": "7.1.3",
"redux": "4.0.5",
"redux-devtools-extension": "2.13.8",
"redux-thunk": "2.3.0"
},

最佳答案

您需要在 pages/_document.js 中对 Material-UI 样式表进行额外设置支持 SSR 样式。

从 MaterialUI v5
如果您没有自定义 _document但是,使用以下代码创建一个:

import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import createEmotionServer from '@emotion/server/create-instance';
import theme from '../src/theme';
import createEmotionCache from '../src/createEmotionCache';

class MyDocument extends Document {
static async getInitialProps(ctx) {
const originalRenderPage = ctx.renderPage;
const cache = createEmotionCache();
const { extractCriticalToChunks } = createEmotionServer(cache);

ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => function EnhanceApp(props) {
return <App emotionCache={cache} {...props} />;
}
});

const initialProps = await Document.getInitialProps(ctx);
const emotionStyles = extractCriticalToChunks(initialProps.html);
const emotionStyleTags = emotionStyles.styles.map((style) => (
<style
data-emotion={`${style.key} ${style.ids.join(' ')}`}
key={style.key}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: style.css }}
/>
));

return {
...initialProps,
emotionStyleTags,
};
}

render() {
return (
<Html lang="en">
<Head>
<meta name="theme-color" content={theme.palette.primary.main} />
<link rel="shortcut icon" href="/static/favicon.ico" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
{this.props.emotionStyleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
};
然后,在您的 _app .
import React from 'react';
import Head from 'next/head';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { CacheProvider } from '@emotion/react';
import theme from '../src/theme';
import createEmotionCache from '../src/createEmotionCache';

const clientSideEmotionCache = createEmotionCache();

export default function MyApp(props) {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;

return (
<CacheProvider value={emotionCache}>
<Head>
<meta name="viewport" content="initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</CacheProvider>
);
}

在 MaterialUI v5 之前
如果您没有自定义 _document.js但是,使用以下代码创建一个:
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/styles';

class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;

ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheets.collect(<App {...props} />)
});

const initialProps = await Document.getInitialProps(ctx);

return {
...initialProps,
// Styles fragment is rendered after the app and page rendering finish.
styles: [
...React.Children.toArray(initialProps.styles),
sheets.getStyleElement()
]
};
}

render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

export default MyDocument;
然后,您可以删除自定义 _app.js 中的服务器端注入(inject)样式。 .
useEffect(() => {
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles);
}
}, []);

更多详情请查看 Material-UI official documentation .

关于javascript - 在 Next JS 中,Material UI makeStyles 在刷新时撤消自定义 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66089290/

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