【问题标题】:Using custom styles from theme in material ui without makeStyles在没有 makeStyles 的材料 ui 中使用来自主题的自定义样式
【发布时间】:2020-11-11 18:47:14
【问题描述】:

我想知道是否有一种方法可以访问 MyComponent 中的 theme.customElements.acitonButton 而无需使用 makeStyles?例如,我可以输入 className={theme.customElements.actionButton} 吗?

theme.js

const theme = createMuiTheme({
   customElements: {
     actionButton: {
       backgroundColor: '#007AFF'
     }
   }
})


export default theme

MyComponent.tsx

import { makeStyles, createStyles, Theme } from '@material-ui/core'

// wondering if i can remove makeStyles and somehow access styles set in theme.js and add to <IconButton />?
const useStyles: any = makeStyles((theme: Theme) => {
  return createStyles({
    actionButton: theme.customElements.actionButton
  })
})


const MyComponent: React.FunctionComponent<MyComponentProps> = props => {
   const classes = useStyles()
   <IconButton className={classes.actionButton} />
}

【问题讨论】:

    标签: javascript material-ui themes formik-material-ui


    【解决方案1】:

    您可以在主题中覆盖组件或元素的样式。 为此,您需要在主题文件夹中创建一个名为 overrides 的文件夹,并创建一个与要覆盖其主题的组件同名的文件。

    然后你可以像这样改变组件样式。

    export default {
    elevation1: {
        boxShadow: '0 0 0 1px rgba(63,63,68,0.05), 0 1px 3px 0 rgba(63,63,68,0.15)'
    }
    

    };

    您还需要将主题提供程序添加到 App.js。

    import React from 'react';
    import ThemeProvider from '@material-ui/styles/ThemeProvider';
    import CssBaseline from '@material-ui/core/CssBaseline';
    import {darkBlueTheme} from './theme';
    import Routes from './Routes';
    
    function App() {
        return (
            <StateProvider reducer={appReducer} initialState={getInitialState()}>
                <ThemeProvider theme={darkBlueTheme}>
                   App CODE HERE
                </ThemeProvider>
            </StateProvider>
        );
    }
    
    export default App;
    

    【讨论】:

    • 你能分享一下elevation1组件的外观吗?您是在命名组件 elevation1 还是将一些道具传递给它?
    • 不,该组件是 MUIPaper (material-ui.com/components/paper)。由于这是一个覆盖,您需要添加 ThemeProvider - 使用代码编辑原始答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多