在没有makeStyles的材质ui中使用主题中的自定义样式

时间:2020-11-11 18:47:14

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

我想知道是否有一种无需使用makeStyles即可访问MyComponent中的theme.customElements.acitonButton的方法吗?例如,我可以以某种方式输入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} />
}

1 个答案:

答案 0 :(得分:0)

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

a folder structure like this

然后您可以像这样更改组件样式。

component's overridden style

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;