React + Material UI - Переопределение MuiTheme в компоненте withStyles - PullRequest
1 голос
/ 20 мая 2019

Я использую Материал UI с React. Попытка переопределить стиль компонента TextField, который был настроен с использованием глобальной темы. Я настроил глобальную тему для всех TextField компонентов в приложении.

Соответствующий код:

theme-engine.js:

export const theme = brand => createMuiTheme({
    palette: {
        primary: {
            main: Brand.getColors(brand).primary
        },
        secondary: {
            main: Brand.getColors(brand).secondary
        },
    },
    typography: {
        fontFamily,
        fontSize: 14,
        htmlFontSize: 16
    },
    overrides: {
        MuiInputBase: {
            root: {
                color: 'rgba(0, 0, 0, 0.87)',
                fontSize: '14px',
                fontFamily,
                '&:after': {
                    borderBottom: Brand.getColors(brand).primary,
                    backgroundColor: Brand.getColors(brand).primary,
                    height: 1
                },
                '&:focused:not($disabled):not($error):before': {
                    borderBottom: Brand.getColors(brand).primary,
                    backgroundColor: Brand.getColors(brand).primary,
                    height: 1
                },
                '&$error:before': {
                    borderBottom: '#f44336',
                    backgroundColor: '#f44336',
                    height: 1
                },
            },
        },
        MuiInput: {
            root: {
                fontFamily
            },
            underline: {
                '&:hover:not($disabled):not($error):not($focused):before': {
                    borderBottom: '#e0e0e0',
                    backgroundColor: '#e0e0e0',
                    height: 1
                },
                '&:not($disabled):not($error):after': {
                    borderBottom: Brand.getColors(brand).primary,
                    backgroundColor: Brand.getColors(brand).primary,
                    height: 1
                },
                '&$error:before': {
                    borderBottom: '#f44336',
                    backgroundColor: '#f44336',
                    height: 1
                },
                '&$error:after': {
                    borderBottom: '#f44336',
                    backgroundColor: '#f44336',
                    height: 1
                },
            },
        },
        MuiSvgIcon: {
            colorPrimary: {
                fill: '#74797b'
            },
            colorSecondary: {
                fill: Brand.getColors(brand).primary,
            }
        },
    }
});

container.js:

 render() {
        return (
            <MuiThemeProvider theme={theme(brand)}>
                //stuff goes here
            </MuiThemeProvider>
        )
    }

Теперь в одном из компонентов я использую значок для TextField и хочу, чтобы подчеркивание также появилось под значком. Для этого я пытаюсь переопределить предоставленную тему, которая не работает. Применяются стили из theme-engine, но локальное переопределение не работает.

some-component.js

import TextField from '@material-ui/core/TextField';
import {withStyles} from '@material-ui/core/styles';
const TextFieldIcon = withStyles(theme => ({
    root: {
        underline: {
            color: 'red',
            height: 4,
            '&:before': {
                borderBottom: `1px solid #e0e0e0`,
                bottom: '-8px',
                left: '-32px'
            },
            '&:hover:not($disabled):not($error):not($focused):before': {
                borderBottom: 'red',
                backgroundColor: 'red',
                height: 1,
                bottom: '-8px',
                left: '-32px'
            },
            '&:not($disabled):not($error):after': {
                height: 2,
                bottom: '-8px',
                left: '-32px'
            },
            '&$error:before': {
                height: 1,
                bottom: '-8px',
                left: '-32px'
            },
            '&$error:after': {
                height: 1,
                bottom: '-8px',
                left: '-32px'
            },
        },
    }
}))(TextField);

class SomeComponent extends Component{
        //Lifecycle methods to make your life easier....or difficult.

        render(){
            return(
                <TextFieldIcon {...assign props and stuff} /> //Styles are not applied
            )
        }
}

Итак, вопрос в том, что я хочу сохранить собственную глобальную тему, но также переопределить некоторые ее части в моем компоненте. Любые вклады приветствуются.

1 Ответ

1 голос
/ 20 мая 2019

Я вижу несколько проблем:

  • Вы не должны иметь правило underline, вложенное в root.Вы должны иметь возможность просто удалить внешний root блок
  • . Чтобы ссылаться на другие правила (например, $disabled, $error и $focused), эти правила должны быть определены вобъект стиля, который вы передаете withStyles
  • Классы, сгенерированные withStyles, являются классами для Input компонента, заключенного в TextField, поэтому вам нужно передать их через свойство InputProps

Ниже приведен рабочий пример необходимого синтаксиса.Я не пытался оценить, выполняют ли стили то, что вы намереваетесь, но они определенно применяются.

import React from "react";

import TextField from "@material-ui/core/TextField";
import { withStyles } from "@material-ui/core/styles";
const styles = theme => ({
  underline: {
    color: "red",
    height: 4,
    "&:before": {
      borderBottom: `1px solid #e0e0e0`,
      bottom: "-8px",
      left: "-32px"
    },
    "&:hover:not($disabled):not($error):not($focused):before": {
      borderBottom: "red",
      backgroundColor: "red",
      height: 1,
      bottom: "-8px",
      left: "-32px"
    },
    "&:not($disabled):not($error):after": {
      height: 2,
      bottom: "-8px",
      left: "-32px"
    },
    "&$error:before": {
      height: 1,
      bottom: "-8px",
      left: "-32px"
    },
    "&$error:after": {
      height: 1,
      bottom: "-8px",
      left: "-32px"
    }
  },
  disabled: {},
  error: {},
  focused: {}
});
const CustomTextField = ({ classes, ...other }) => {
  return <TextField InputProps={{ classes: classes }} {...other} />;
};

export default withStyles(styles)(CustomTextField);

Edit Custom TextField

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...