簡體   English   中英

如何從我自己的 scss/css 調色板中將道具作為變量動態分配給 colors 並做出反應?

[英]How can i dynamically assign the props as variables to colors from my own color pallet in scss/css with react?

我正在使用以下道具調用組件“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 根處設置變量並使用變量 function var() 訪問它,它工作正常。 但由於一些限制,我不想使用這種方法。 還因為顏色托盤列表很大,我不想為所有這些使用單獨的類。

我正在尋找其他解決方案或不同的方法。

因此,您可以使用自定義 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>
  );
};

根據您的代碼風格,您可以將querySelector替換為ref

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM