首页 > 解决方案 > 我如何通过反应动态地将道具作为变量分配给我自己在 scss/css 中的颜色托盘中的颜色?

问题描述

我正在使用以下道具调用组件“MyRadioButton”:

<MyRadioButton
          label="Radio Group"
          theme="custom-red"  //this line
          error="Field is required "
          radioBtns={options}
          id="radioBtns"
          name="radioBtns"
          getValue={this.getValue}
        />

我创建了一个反应组件“MyRadioButton”,它将接受颜色名称(主题)作为道具。

export const MyRadioButton = props => {
const {theme} = props;
return (
    <div className="my-radio-buttons"> // need to use theme here
      <input
              onChange={onChange}
              type="radio"   
       />
     </div>
)}

基于这个道具,我想在我的组件 scss 文件中分配变量,它将从我自定义的颜色托盘中获取颜色代码。

我的单选按钮.scss

/* custom color pallet */
  $custom-orange: #F060D6;
  $custom-red: #BB532E;
  $custom-blue: #4C9FEB;

.my-radio-buttons {
  .input{
     border: 2px solid $custom-red; // i want to assign the color variable based on input prop value to this property
   }
}

我已经尝试使用 javascript 在 css root 设置变量并使用变量函数 var() 访问它,它工作正常。但由于一些限制,我不想使用这种方法。还因为颜色托盘列表很大,我不想为所有这些使用单独的类。

我正在寻找其他解决方案或不同的方法。

标签: javascriptcssreactjssass

解决方案


因此,您可以使用自定义 css 变量和您传递的主题属性的组合。在您的 css 中,您将定义边框的基色,例如:

.my-radio-buttons {
  --theme-color: red;

  input {
     border: 2px solid var(--theme-color);
   }
}

这可以由您的组件通过componentDidMountuseEffect使用传递的主题更新:

const MyRadioButton = props => {
  const { theme } = props;

  React.useEffect(() => {
    const input = document.querySelector(".my-radio-buttons input");

    input.style.setProperty("--theme-color", props.theme);
  }, []);

  return (
    <div className="my-radio-buttons">
      <input />
    </div>
  );
};

根据您的代码风格,您可以将 替换querySelectorref.


推荐阅读