【发布时间】:2020-04-14 17:30:41
【问题描述】:
在 React 中,我有一个功能组件,用于验证 props 并为任何非必需的 props 实现默认 props。我还使用 mui 的 makeStyles 来获取 theme 对象以将样式应用于我的组件。
我的问题是如何将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;
【问题讨论】:
标签: reactjs material-ui react-props