【问题标题】:How to use theme in styles for custom class components如何在自定义类组件的样式中使用主题
【发布时间】:2020-01-17 20:38:57
【问题描述】:

我想在我自己的基于类的组件中使用一个主题。我无法进行任何工作,文档中的所有示例都是针对功能组件的。基本上定义了主题,我想用它来设置我自己的组件的样式,这样我就可以避免重复自己并在更高级别更改代码,并且它会随处更改。

我的 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

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;

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您不能将makeStyles 与类组件一起使用。 makeStyles 返回一个只能在函数组件中使用的自定义钩子。对于类组件,您可以使用withStyles 来利用所有相同的功能。 withStyles 包装你的组件并注入一个 classes 属性。

    以下是基于您问题中的代码的工作示例:

    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);
    

    相关答案:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2018-01-15
    • 2013-07-04
    • 2011-05-28
    • 2019-03-23
    • 1970-01-01
    相关资源
    最近更新 更多