【问题标题】:Using classnames to dynamically style component with CSS based on props value使用类名根据 props 值使用 CSS 动态设置组件样式
【发布时间】:2020-03-14 03:27:54
【问题描述】:

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

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

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

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

TIA

【问题讨论】:

    标签: javascript css reactjs material-ui class-names


    【解决方案1】:

    您需要将props 传递给您的useStyles(props) 函数,然后您可以在其中使用props,如styled-component。

    文档链接: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

    希望有帮助

    【讨论】:

    • 太棒了,很有魅力。和一个很好的干净的解决方案。谢谢。
    • 不客气,实际上我从来没有像你那样直接覆盖 MUI 类并将样式传递给classes,我也从你那里学到了一些新东西。几个月以来,我只使用 className={cx({...}}
    猜你喜欢
    • 1970-01-01
    • 2020-12-09
    • 2019-03-21
    • 2020-05-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2016-06-08
    相关资源
    最近更新 更多