由于classNames的分配方式不同,我在Material-UI组件中的样式的客户端和服务器端呈现之间存在差异 .
首次加载页面时正确分配了classNames,但刷新页面后,classNames不再匹配,因此组件将失去其样式 . 这是我在控制台上收到的错误消息:
警告:Prop className不匹配 . 服务器:“MuiFormControl-root-3 MuiFormControl-marginNormal-4 SearchBar-textField-31”客户端:“MuiFormControl-root-3 MuiFormControl-marginNormal-4 SearchBar-textField-2”
我已经关注了Material-UI TextField example docs及其随附的Code Sandbox example,但我似乎无法弄清楚导致服务器和客户端classNames之间差异的原因 .
添加带有删除'x'图标的Material-UI Chips时,我遇到了类似的问题 . 刷新后以“1024px”的宽度渲染的“x”图标 . 同样的根本问题是该图标没有收到正确的样式类 .
关于Stack Overflow的一些问题解决了为什么客户端和服务器可能以不同方式呈现classNames(例如需要升级到@ Material-UI /核心版本^ 1.0.0,使用自定义server.js,以及在setState中使用Math.random ),但这些都不适用于我的情况 .
我不知道this Github discussion是否有帮助,但可能不会因为他们使用的是Material-UI测试版 .
重现的最小步骤:
创建项目文件夹并启动节点服务器:
mkdir app
cd app
npm init -y
npm install react react-dom next @material-ui/core
npm run dev
编辑package.json:
添加到'scripts': "dev": "next",
app / pages / index.jsx:
import Head from "next/head"
import CssBaseline from "@material-ui/core/CssBaseline"
import SearchBar from "../components/SearchBar"
const Index = () => (
<React.Fragment>
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charSet="utf-8" />
</Head>
<CssBaseline />
<SearchBar />
</React.Fragment>
)
export default Index
app / components / SearchBar.jsx:
import PropTypes from "prop-types"
import { withStyles } from "@material-ui/core/styles"
import TextField from "@material-ui/core/TextField"
const styles = (theme) => ({
container: {
display: "flex",
flexWrap: "wrap",
},
textField: {
margin: theme.spacing.unit / 2,
width: 200,
border: "2px solid red",
},
})
class SearchBar extends React.Component {
constructor(props) {
super(props)
this.state = { value: "" }
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({ value: event.target.value })
}
handleSubmit(event) {
event.preventDefault()
}
render() {
const { classes } = this.props
return (
<form
className={classes.container}
noValidate
autoComplete="off"
onSubmit={this.handleSubmit}
>
<TextField
id="search"
label="Search"
type="search"
placeholder="Search..."
className={classes.textField}
value={this.state.value}
onChange={this.handleChange}
margin="normal"
/>
</form>
)
}
}
SearchBar.propTypes = {
classes: PropTypes.object.isRequired,
}
export default withStyles(styles)(SearchBar)
在浏览器 localhost:3000
中访问该页面并看到:
red border around TextField component
刷新浏览器并看到:
TextField component's styles are gone
请注意,TextField周围的红色边框消失 .
相关人员:
-
"react":16.4.0
-
"react-dom":16.4.0
-
"next":6.0.3
-
"@material-ui/core":1.2.0
1 回答
问题是服务器端生成类名,但样式表不会自动包含在HTML中 . 您需要显式提取CSS并将其附加到服务器端呈现组件的UI . 整个过程在这里解释:https://material-ui.com/guides/server-rendering/