使用 material-ui 的 makeStyles,是否可以选择在应用所有样式的对象中传播道具?
即:
const useStyles = makeStyles(theme) => ({
card: {
...props # <- props has stuff like backgroundColor, fontSize etc.
},
thisWorks: {
backgroundColor: (props) => props.backgroundColor,
fontSize: (props) => props.fontSize,
}
})
答案 0 :(得分:1)
是的,这是可能的。查看文档 here。
您可以将 props 传递给您的 useStyles
钩子。
由于您将 props
作为 makeStyles
中声明函数的参数,因此您必须使用函数。但这并不妨碍您使用扩展运算符。
请记住,您需要在最后返回一个对象
const useStyles = makeStyles((theme) => ({
// use the spread operator
card: (props) => ({
// dynamic styles from props
...props,
// static styles
border: "1px solid red"
}),
// more explicit way if you need just specific props
card2: (props) => {
const { backgroundColor, color } = props;
return {
backgroundColor,
color
};
}
}));
...
const MyComponent = () => {
const myProps = {
backgroundColor: "#000",
fontSize: "32px",
};
const classes = useStyles(myProps)
return (<div className={classes.card}>
...
</div>
)
}