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