【发布时间】:2023-01-19 08:58:38
【问题描述】:
我一直在使用 typescript 在 create-React-App 上实现 MUI (v5)。我有一个定制的主题和所有。
我想创建一个 MyButton 组件,它采用引用我的 theme.palette 的 buttonType 道具(typeof 字符串)并将其传递给它所构建的 MuiButton 以定义其颜色。
我尝试了几种方法。
- MUIButton 的颜色道具似乎不接受任何变量,即使它们的类型与定义它的枚举相匹配。 doc here
- 除非指定 !important doc here,否则不会应用这些类
- 将 buttonType 传递给 useStyle 会返回错误。 doc here
这里的代码:
在 App.tsx 文件中:
function App() {
return (
<div className="App">
<h1>My customized buttons</h1>
<div className="buttonContainer">
<MyButton buttonType={'primary'}/>
<MyButton buttonType={'secondary'}/>
<MyButton buttonType={'warning'}/>
<MyButton buttonType={'error'}/>
<MyButton buttonType={'success'}/>
</div>
</div>
);
}
在 MyButton.tsx 文件中:
import MuiButton, {ButtonProps as MuiButtonProps} from '@mui/material/Button';
import {makeStyles} from '@material-ui/core/styles';
const useStyles: any = makeStyles((theme: Theme) => ({
root: {
border: '3px solid red',
borderRadius: 5,
padding: theme.spacing(1, 2),
margin: theme.spacing(2),
},
}));
const useButtonStyles: any = makeStyles((theme: Theme) => ({
root: {
border: '3px solid blue',
backgroundColor: (buttonType: string )=>buttonType,
},
}));
function MyButton({buttonType = 'primary'}: MyButtonProps) {
const classes = useStyles();
const buttonClasses = useStyles(buttonType);
...
return(
<div>
<MuiButton classes={classes}>Button only makeStyle</MuiButton>
<MuiButton classes={classes} color={'primary' === buttonType ? 'primary' : buttonType}>Button {buttonType}</MuiButton>
<MuiButton classes={buttonClasses}> Color defined in MakeStyle with {buttonType} </MuiButton>
{/*color passed as string get theme.palette colors without issue */}
{/*<Button color="error">Button Error</Button>*/}
{/*<Button color="warning">Button warning</Button>*/}
{/*<Button color="success">Button success</Button>*/}
</div>
);
}
export default MyButton;
interface MyButtonProps {
buttonType: 'inherit' | 'primary' | 'secondary' | 'success' | 'error' | 'info' | 'warning' | string,
}
【问题讨论】:
标签: reactjs typescript material-ui react-tsx