你们在使用Material UI的withStyles钩子向组件添加自定义样式时遇到了这种情况。
这是我的package.json:
{
"name": "socialapp-client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.11.0",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.20.0",
"dayjs": "^1.8.35",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "<link to my Google firebase API>"
}
这是App.js代码
import React, { Component } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { Home } from "./pages/home";
import { login } from "./pages/login";
import { signup } from "./pages/signup";
import { Navbar } from "./components/Navbar";
import { ThemeProvider, createMuiTheme } from "@material-ui/core/styles";
import "./App.css";
const theme = createMuiTheme({
palette: {
primary: { main: "#29b6f6" },
secondary: { main: "#ffa726" },
},
});
class App extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<div className="App">
<Router>
<Navbar></Navbar>
<div className="container">
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={login} />
<Route path="/signup" component={signup} />
</Switch>
</div>
</Router>
</div>
</ThemeProvider>
);
}
}
export default App;
这是登录页面的代码:
import React, { Component } from 'react'
import withStyles from '@material-ui/core/styles/withStyles';
const styles = {
mantra:{
textAlign: 'center'
}
}
export class login extends Component {
render() {
const { classes } = this.props;
console.log(classes.mantra)
return (
<div>
<h1>login Page</h1>
</div>
)
}
}
export default withStyles(styles)(login);
根据对文档的检查,我可以正确地进行所有操作,但是我被错误阻止
TypeError: Cannot read property 'mantra' of undefined