【问题标题】:How to apply CSS variable on dynamic CSS class in dynamic component如何在动态组件中的动态 CSS 类上应用 CSS 变量
【发布时间】:2023-01-21 03:43:03
【问题描述】:

我有库组件,并且我创建了一些组件,但是当我在具有不同样式的父组件中导入两次组件时,我遇到了 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?没有另一个图书馆?

【问题讨论】:

    标签: css reactjs next.js module styles


    【解决方案1】:

    因为你修改了common topdocument.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 伪类将冒号 : 作为第一个字符,而不是最后一个。

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2013-08-13
      • 1970-01-01
      • 2017-09-19
      • 2020-05-30
      • 2021-04-14
      • 2021-10-17
      • 2018-10-05
      • 1970-01-01
      相关资源
      最近更新 更多