gpt4 book ai didi

reactjs - 如何在样式组件中访问 Material-ui 的主题

转载 作者:行者123 更新时间:2023-12-03 13:22:01 24 4
gpt4 key购买 nike

我正在将 CRA 与 Material-ui 和 Styled Components 类型的样式一起使用。在构建 CSS 时,我想访问 Material-ui 的默认主题。

package.json 的一部分:

  "dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"@material-ui/core": "^4.2.1",
"@material-ui/icons": "^4.2.1",
"@material-ui/styles": "^4.2.1",
"styled-components": "^4.3.2"
}

当我尝试以下 theme 时,theme 存在于 props 上,但它是一个空对象。

StyledApp.js:

import styled from "styled-components";
import Button from "@material-ui/core/Button";

export const StyledButtonUsingTheme = styled(Button)`
//Below will give "Cannot read property 'error' of undefined"
background-color: ${props => props.theme.palette.error.light};
`;

应用程序.js:

import React from "react";
import "./App.css";

import { StylesProvider, ThemeProvider } from "@material-ui/styles";
import { createMuiTheme } from "@material-ui/core/styles";

import { StyledButtonUsingTheme } from "./StyledApp";

function App() {
const defaultTheme = createMuiTheme();

window.console.log("Default theme passing to ThemeProvider", defaultTheme);

return (
<StylesProvider injectFirst>
<ThemeProvider theme={defaultTheme}>
<div className="App">
<StyledButtonUsingTheme variant="outlined">
Styled Button Using Theme
</StyledButtonUsingTheme>
</div>
</ThemeProvider>
</StylesProvider>
);
}

export default App;

App.js 中的 console.log 显示整个主题对象,这就是我传递给 ThemesProvider 的内容。有趣的是 props.theme 就在那里!但遗憾的是没有值(value)观。

最佳答案

您可以使用withTheme:

App.js

import React from "react"
import { ThemeProvider, createMuiTheme } from "@material-ui/core/styles"
import { StyledButton } from "./StyledButton"

const App = () => {

const theme = createMuiTheme();

return (
<ThemeProvider theme={theme}>
<StyledButton />
</ThemeProvider>
)
}

export default App

StyledButton.js

import { styled, withTheme } from "@material-ui/core/styles"
import Button from "@material-ui/core/Button"

export const StyledButton= styled(withTheme(Button))(props => ({
background: props.theme.palette.background.paper,
}))

关于reactjs - 如何在样式组件中访问 Material-ui 的主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57108648/

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