Как передать объект темы material-ui в defaultProps? - PullRequest
1 голос
/ 14 апреля 2020

В React у меня есть функциональный компонент, который проверяет реквизиты и реализует реквизиты по умолчанию для любых ненужных реквизитов. Я также использую mui makeStyles для захвата объекта theme, чтобы применить стилизацию к моим компонентам.

У меня вопрос , как можно go передать объект темы makeStyles вниз к defaultProps, чтобы избежать жестких значений?

import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';


const useStyles = makeStyles(theme => ({
  componentStyle: {
    color: `${theme.palette.light.main}`,  // just like how I'm accessing `theme` here, I'd like to access in `defaultProps`
  },
  componentContainer: ({ backgroundColor }) => {
    return { backgroundColor };
  },
}));


const Example = ({ backgroundColor }) => {
  const classes = useStyles({ backgroundColor });

  return (
    <div className={classes.componentStyle} >
      <div className={classes.componentContainer} /> // use default styling using `theme` if none is provided
    </div>
  )

}


Example.propTypes = {
  backgroundColor: PropTypes.string,
};


Example.defaultProps = {
  backgroundColor: `${theme.palette.light.main}`,  // I want to access `theme` here and do the following. While `backgroundColor: 'white'` will work I want to avoid hard keying values. 
};


export default Example;

РЕДАКТИРОВАТЬ: на основе решения, предоставленного @Fraction ниже, я буду двигаться вперед.

import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';


const useStyles = makeStyles(theme => ({
  componentStyle: {
    color: `${theme.palette.light.main}`,
  },
  componentContainer: ({ backgroundColor }) => {
    return { 
      backgroundColor: backgroundColor || `${theme.palette.light.main}`
    };
  },
}));


const Example = ({ backgroundColor }) => {
  const classes = useStyles({ backgroundColor });

  return (
    <div className={classes.componentStyle} >
      <div className={classes.componentContainer} />
    </div>
  )

}


Example.propTypes = {
  backgroundColor: PropTypes.string,
};


Example.defaultProps = {
  backgroundColor: null, 
};


export default Example;

Ответы [ 2 ]

1 голос
/ 15 апреля 2020

Вам не нужно передавать объект темы makeStyles в defaultProps, просто используйте Логическое ИЛИ ||, чтобы установить для свойства backgroundColor значение theme.palette.light.main когда переданным аргументом является любое ложное значение, например: (0, '', NaN, null, undefined):

const useStyles = makeStyles(theme => ({
  componentStyle: {
    color: `${theme.palette.light.main}`,  // just like how I'm accessing `theme` here, I'd like to access in `defaultProps`
  },
  componentContainer: ({ backgroundColor }) => ({ 
    backgroundColor: backgroundColor || theme.palette.light.main,
  }),
}));
1 голос
/ 14 апреля 2020

Я бы посоветовал не передавать тему как реквизит, а использовать контекст темы.

Я делаю это во всех приложениях, над которыми я работаю, и является гибким и предотвращает бурение реквизита.

В компоненте верхнего уровня, например, App.tsx, укажите поставщика темы пользовательского интерфейса для материала:

import { ThemeProvider } from '@material-ui/core/styles';
import DeepChild from './my_components/DeepChild';

const theme = {
  background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
};

function Theming() {
  return (
    <ThemeProvider theme={theme}>
      <DeepChild />
    </ThemeProvider>
  );
}

Затем в ваших компонентах, нуждающихся в теме: (согласно https://material-ui.com/styles/advanced/#accessing - -the-in-a-component ):

import { useTheme } from '@material-ui/core/styles';

function DeepChild() {
  const theme = useTheme();
  return <span>{`spacing ${theme.spacing}`}</span>;
}

...