简体   繁体   English

如何在动态组件中将CSS变量应用于动态CSS class

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

I have library components, and I create some components, but I have a problem with CSS when importing twice a component in a parent component with different styles.我有库组件,并且创建了一些组件,但是当在具有不同 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: CSS:

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

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

When I import this component and set a different color:当我导入这个组件并设置不同的颜色时:

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

...both components get blue color! ...两个组件都变成蓝色!

I couldn't use the style module, have many errors!我无法使用样式模块,有很多错误!

How can I best use dynamic CSS?我怎样才能最好地使用动态 CSS? Without another library?没有另一个图书馆?

Because you modify the CSS variable/property on the common top document.documentElement , it will affect all your Elements.因为您修改了公共顶部document.documentElement上的 CSS 变量/属性,它会影响您的所有元素。

If you want to apply it only on your React component, then simply set it on that component Element.如果你只想在你的 React 组件上应用它,那么只需将它设置在该组件 Element 上。 To get a handle to such Element, you can use the useRef hook:要获取此类元素的句柄,您可以使用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>;
};

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


BTW, there is a typo in your CSS: :root pseudo-class has the colon : as 1st character, not last.顺便说一句,你的 CSS: :root伪类有一个冒号:作为第一个字符,而不是最后一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM