[英]How can I use a Material-UI theme palette color in a custom React component?
I have a custom Sidebar component for which I would like the background color to use Material-UI's primary palette color.我有一个自定义侧边栏组件,我希望其背景颜色使用 Material-UI 的主调色板颜色。
Sidebar.js
import styles from '../styles/Home.module.css';
export default function Sidebar() {
return (
<div className={styles.sidebar}>
<hr className={styles.divider} />
</div>
)
}
Home.module.css
.sidebar {
left: 0;
top: 64px;
height: 100vh;
z-index: 20;
width: 60px;
position: fixed;
}
_app.js
import '../styles/globals.css';
import NavBar from '../components/NavBar';
import Sidebar from '../components/Sidebar';
function MyApp({ Component, pageProps }) {
return (
<>
<NavBar></NavBar>
<Sidebar color="primary"></Sidebar>
<Component {...pageProps} />
</>
)
}
export default MyApp
Obviously the <Sidebar color="primary">
doesn't work.显然
<Sidebar color="primary">
不起作用。 I'm not sure how to achieve this.我不确定如何实现这一目标。
You can access the theme values by using a HOC or the useThemee
hook.您可以使用 HOC 或
useThemee
挂钩访问主题值。
https://material-ui.com/styles/advanced/#accessing-the-theme-in-a-component https://material-ui.com/styles/advanced/#accessing-the-theme-in-a-component
From there, you can get the theme color and pass it down to the Sidebar
component.从那里,您可以获取主题颜色并将其传递给
Sidebar
组件。
function MyApp({ Component, pageProps }) {
const theme = useTheme();
return (
<>
<NavBar></NavBar>
<Sidebar color={theme.palette.primary1Color}></Sidebar>
<Component {...pageProps} />
</>
)
}
This is how I got it working using useTheme()
at nipuna's suggestion.这就是我在 nipuna 的建议下使用
useTheme()
使其工作的方式。
Sidebar.js
import styles from '../styles/Home.module.css';
import { useTheme } from '@material-ui/core/styles';
export default function Sidebar() {
const theme = useTheme();
return (
<div style={{ backgroundColor: theme.palette.primary.main }} className={styles.sidebar}>
<hr className={styles.divider} />
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.