如何在自定义类组件的样式中使用主题 [英] How to use theme in styles for custom class components
问题描述
我想在基于类的我自己的组件的某些部分中使用主题.我什么都无法工作,文档中的所有示例都是针对功能组件的.基本上,主题是定义好的,我想用它来设置自己的组件样式,这样我就可以避免重复自己并在更高级别上更改代码,并且该代码随处可见.
I want to use a theme in parts of my own components that are class based. I cannot get anything to work, all examples in the documentation is for functional components. Basically the theme is defined and I want to use it to style my own components so I can avoid repeating myself and change the code at the higher level and it change everywhere.
我的App.js
import { ThemeProvider } from '@material-ui/styles';
import { createMuiTheme } from '@material-ui/core/styles';
const theme = createMuiTheme({
palette: {
primary: {
light: '#757ce8',
main: '#3f50b5',
dark: '#002884',
contrastText: '#fff',
},
},
overrides: {
MuiOutlinedInput: {
disabled: true,
input: {
color: 'red'
}
}
}
});
export default class App extends React.Component {
render() {
return (
<ThemeProvider theme={theme}>
<Nav />
</ThemeProvider>
);
}
}
我的问题文件Nav.js
My Problem file, Nav.js
import React from 'react';
import SearchBar from './SearchBar';
import { makeStyles } from '@material-ui/styles';
const styles = makeStyles(theme => ({
root: {
background: theme.background,
},
}));
class Nav extends React.Component {
render() {
const classes = styles();
return(
<div className={classes.root}>
<SearchBar />
</div>
)
}
}
export default Nav;
推荐答案
您不能将makeStyles
与类组件一起使用. makeStyles
返回一个只能在功能组件中使用的自定义钩子.对于类组件,您可以使用 withStyles 来利用所有相同的功能一个>. withStyles
包装您的组件并注入一个classes
道具.
You cannot use makeStyles
with class components. makeStyles
returns a custom hook which can only be used in function components. For class components, you can leverage all of the same functionality using withStyles. withStyles
wraps your component and injects a classes
prop.
下面是一个基于您的问题代码的有效示例:
Below is a working example based on the code in your question:
import React from "react";
import { withStyles } from "@material-ui/core/styles";
class SearchBar extends React.Component {
render() {
return <div>My Search Bar</div>;
}
}
const styles = theme => ({
root: {
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText
}
});
class Nav extends React.Component {
render() {
return (
<div className={this.props.classes.root}>
<SearchBar />
</div>
);
}
}
export default withStyles(styles)(Nav);
相关答案:
- What is the benefit of using withStyles over makeStyles?
- Material-UI withStyles doesn't apply any kind of styles
这篇关于如何在自定义类组件的样式中使用主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!