gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:36 26 4
gpt4 key购买 nike

我正在创建一组使用 CSS 设置样式的可重用组件(包装的 material-ui)。我需要通过传入自定义按钮的 Prop 动态设置组件的宽度。

我想使用类名来合并为 MyButton 定义的常量根样式(我已经在沙盒中剥离了它,但它设置了颜色、图标等)和可以根据传入的 Prop 定义的动态 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
///});

我不明白为什么样式没有应用到页面上传递了 prop 的第一个按钮 - 我可以在控制台上看到应该应用这两种样式。

这里是沙盒: https://codesandbox.io/s/css-styling-custom-muibutton-width-as-prop-36w4r

TIA

最佳答案

你需要将 props 传递给你的 useStyles(props) 函数,然后你可以在其中像 styled-component 一样使用 props

文档链接:https://material-ui.com/styles/basics/#adapting-based-on-props

// 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&hidenavigation=1&theme=dark

希望对你有帮助

关于javascript - 使用类名根据 props 值使用 CSS 动态设置组件样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58920013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com