如何使用CSS模块在React中使用伪类?

问题描述

我处理的示例如下:

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

第二个问题: 在CSS中使用CSS模块使用props的唯一方法是在声明组件的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 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>
  );
}