簡體   English   中英

如何在動態組件中將CSS變量應用於動態CSS class

[英]How to apply CSS variable on dynamic CSS class in dynamic component

我有庫組件,並且創建了一些組件,但是當在具有不同 styles 的父組件中導入兩次組件時,我遇到了 CSS 問題。

import "../myCss.css"
const CircleComponent = ({size , color}) => {
  useEffect(() => {
    if (color)
      document.documentElement.style.setProperty(
        "--color",
        color
      );
    if(size) {
      document.documentElement.style.setProperty(
        "--size",
        `${size}px`
      );
    }
  }, [])

  return <div className="circle"></div>
}

CSS:

root: {
 --color: black;
 --size: 40px
}

.circle{
  height: var(--size);
  width: var(--size);
  background-color: var(--color);
  border-radius: 50%;
}

當我導入這個組件並設置不同的顏色時:

<>
 <CircleComponent color="red" />
 <CircleComponent color="blue" />
</>

...兩個組件都變成藍色!

我無法使用樣式模塊,有很多錯誤!

我怎樣才能最好地使用動態 CSS? 沒有另一個圖書館?

因為您修改了公共頂部document.documentElement上的 CSS 變量/屬性,它會影響您的所有元素。

如果你只想在你的 React 組件上應用它,那么只需將它設置在該組件 Element 上。 要獲取此類元素的句柄,您可以使用useRef掛鈎:

const CircleComponent = ({ size, color }) => {

  const ref = useRef(null);

  useEffect(() => {
    // Modify the property on the element or a parent,
    // not on the common top document
    if (color) ref.current.style.setProperty("--color", color);
    if (size) {
      ref.current.style.setProperty("--size", `${size}px`);
    }
  }, []);

  // Attach the ref with the ref special prop
  return <div ref={ref} className="circle"></div>;
};

演示: https://codepen.io/ghybs/pen/WNKdZro


順便說一句,你的 CSS: :root偽類有一個冒號:作為第一個字符,而不是最后一個。

暫無
暫無

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

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