使用类名根据props值使用CSS动态设置组件样式



我正在创建一组可重用组件(包装材料ui(,这些组件使用CSS进行样式设计。我需要通过传递到自定义按钮中的道具来动态设置组件的宽度。

我想使用类名来合并为MyButton定义的const根样式(我在沙盒中已经把它去掉了,但它设置了颜色、图标等(和动态sizeStyle,后者可以根据传入的道具来定义。

const sizeStyle: JSON =  { minWidth: "300px !important"};

//always apply the buttonstyle, only apply the size style if a width prop has been supplied
const rootStyle: Object = classNames({
buttonStyle: true,
sizeStyle: props.width
///});   

我不明白为什么这个样式没有应用到页面上有道具通过的第一个按钮上——我可以在控制台上看到这两个样式应该被应用。

此处的沙盒:https://codesandbox.io/s/css-styling-custom-muibutton-width-as-prop-36w4r

TIA-

您需要将props传递给useStyles(props)函数,然后在其中可以使用类似props的样式组件。

文档链接:https://material-ui.com/styles/basics/#adapting-基于道具

// eslint-disable-next-line flowtype/no-weak-types
const useStyles = makeStyles({
root: {
//    minWidth: "300px !important",
color: "#565656",
backgroundColor: "salmon",
borderRadius: 2,
textTransform: "none",
fontFamily: "Arial",
fontSize: 16,
letterSpacing: "89%", //'0.09em',
boxShadow:
"0px 1px 5px 0px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 3px 1px -2px rgba(0,0,0,0.12)",
"&:disabled": {
color: "#565656",
opacity: 0.3,
backgroundColor: "#fbb900"
},
minWidth: props => `${props.width}px`,
},
label: {
textTransform: "capitalize",
display: "flex",
whiteSpace: "nowrap"
}
});
// eslint-disable-next-line flowtype/require-return-type
function MyButton(props) {
const { children, ...others } = props;
const classes = useStyles(props);
return (
<Button
{...props}
classes={{
root: classes.root,
label: classes.label
}}
>
{children}
</Button>
);
}

沙盒中的修改版本:https://codesandbox.io/s/css-styling-custom-muibutton-width-as-prop-pcdgk?fontsize=14&隐藏导航=1&主题=深色

希望这能帮助

最新更新