Reactjs 如何在使用css模块的React中使用伪类?
我研究的示例如下: 我有一个按钮组件,它接收背景颜色作为道具。收到的颜色将是鼠标悬停时按钮必须具有的背景 第二个问题: 使用css模块在css中使用道具的唯一方法是在声明组件的js文件中应用内联样式 下面我插入一个代码基(在示例中,默认应用背景色):Reactjs 如何在使用css模块的React中使用伪类?,reactjs,pseudo-class,css-modules,Reactjs,Pseudo Class,Css Modules,我研究的示例如下: 我有一个按钮组件,它接收背景颜色作为道具。收到的颜色将是鼠标悬停时按钮必须具有的背景 第二个问题: 使用css模块在css中使用道具的唯一方法是在声明组件的js文件中应用内联样式 下面我插入一个代码基(在示例中,默认应用背景色): 从“/Button”导入按钮; 导出默认函数App(){ 返回; } 导出默认功能按钮({hoverColor}){ 常量按钮样式={ 背景颜色:hoverColor }; 返回点击我!; } 谢谢您可以使用React-useState钩子来
从“/Button”导入按钮;
导出默认函数App(){
返回;
}
导出默认功能按钮({hoverColor}){
常量按钮样式={
背景颜色:hoverColor
};
返回点击我!;
}
谢谢您可以使用React-useState钩子来实现所需的功能:(您的按钮组件应该如下所示)
import React,{useState}来自“React”;
导出默认功能按钮({hoverColor}){
const[color,setColor]=useState(“”);
常量按钮样式={
背景颜色
};
返回(
setColor(hoverColor)}//设置用户将鼠标悬停在按钮上时的颜色
onMouseOut={()=>setColor(“”}//否则将color设置为空字符串
>
点击我!
);
}
这是否回答了您的问题@PunitMakwana您好,我已经阅读了这个主题,我想用css模块管理css,不需要其他库的支持,我想了解是否可以只使用css模块和内联的伪类。您需要js库中的一些第三方css来做这件事。根据你的经验,我建议你使用emotionjs。你认为这是解决这个问题的唯一方法吗?谢谢,这是一个冗长的解决方案,但它是有效的。我认为在内联css中使用伪类是有语法的。我们还有其他解决方案吗
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>;
}
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>
);
}