【问题标题】:How do you use Pseudo-classes in React using css modules?你如何使用 CSS 模块在 React 中使用伪类?
【发布时间】:2021-02-14 09:04:18
【问题描述】:

我处理的示例如下:

我有一个按钮组件接收背景颜色作为道具。接收到的颜色将是悬停时按钮必须具有的背景。

第二个问题: 在css中使用props,使用css模块的唯一方法是在声明组件的js文件中应用内联样式?

下面我插入一个代码库(在示例中默认应用背景颜色):

import Button from "./Button";

export default function App() {
  return <Button hoverColor={"red"} />;
}

...

export default function Button({ hoverColor }) {
  const buttonStyle = {
    backgroundColor: hoverColor
  };
  return <button style={buttonStyle}>click me!</button>;
}

谢谢

【问题讨论】:

  • 这能回答你的问题吗? React pseudo selector inline styling
  • @PunitMakwana 嗨,我已经阅读了这个主题,我想用 css 模块管理 css,没有其他库的支持,我想了解是否可以使用伪仅具有 css 模块和内联的类。
  • 您需要在 js 库中添加一些第三方 css 来执行此操作。我会推荐emotionjs
  • 根据您的经验,您认为这是解决此问题的唯一方法吗?

标签: reactjs pseudo-class css-modules


【解决方案1】:

您可以使用 React useState Hook 来实现所需的功能:(您的 Button 组件应如下所示)

import React, { useState } from "react";

export default function Button({ hoverColor }) {
  const [color, setColor] = useState("");

  const buttonStyle = {
    backgroundColor: color
  };
  return (
    <button
      style={buttonStyle}
      onMouseOver={() => setColor(hoverColor)} //set the color when user hovers over the button
      onMouseOut={() => setColor("")} //set color to an empty string otherwise
    >
      click me!
    </button>
  );
}


【讨论】:

  • 谢谢,它作为一个解决方案很冗长,但它确实有效。我认为有一种语法可以在内联 css 中使用伪类。
  • 我们还有其他解决方案吗
猜你喜欢
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2020-06-28
  • 2017-01-13
  • 2017-05-07
  • 2020-09-17
  • 2011-07-20
相关资源
最近更新 更多