Css 使用道具设置'&;:悬停';背景色
我正在包装Material UI的芯片组件,以便可以为Css 使用道具设置'&;:悬停';背景色,css,reactjs,material-ui,jsx,Css,Reactjs,Material Ui,Jsx,我正在包装Material UI的芯片组件,以便可以为颜色道具传入除“主”和“次”之外的值。如果芯片是可点击的,我还想保持悬停效果,这样当光标在芯片上时,芯片会转换成不同的颜色。颜色作为道具传入,因此设置backgroundColor和color非常简单: <Chip style={{ backgroundColor: props.backgroundColor, color: props.color }} /> 但是,由于我也希望将悬停颜色作为道具传
颜色
道具传入除“主”和“次”之外的值。如果芯片是可点击的,我还想保持悬停效果,这样当光标在芯片上时,芯片会转换成不同的颜色。颜色作为道具传入,因此设置backgroundColor
和color
非常简单:
<Chip
style={{
backgroundColor: props.backgroundColor,
color: props.color
}}
/>
但是,由于我也希望将悬停颜色作为道具传递,因此我需要执行以下操作:
<Chip
style={{
backgroundColor: props.backgroundColor,
color: props.color,
'&:hover': {
backgroundColor: props.hoverBackgroundColor,
color: props.hoverColor
}
}}
/>
<CustomChip
label="Custom Chip 1"
color="green"
backgroundColor="#ccf"
onClick={() => {
console.log("clicked 1");
}}
/>
<CustomChip
label="Custom Chip 2"
color="#f0f"
backgroundColor="#fcc"
hoverBackgroundColor="#afa"
onClick={() => {
console.log("clicked 2");
}}
/>
但是,据我所知,
&:hover
(据我所知)不能在样式中使用。通常,&:hover
会在styles对象内部使用,该对象通过styles
传递到,但我无法从中访问道具。有什么建议吗?您可以通过创建自己的定制芯片组件来实现这一点。为了能够使用道具控制样式,可以使用。makeStyles
函数返回一个钩子,该钩子可以接受一个对象参数,用于为样式提供变量
以下是一个可能的定制芯片实现:
import React from "react";
import Chip from "@material-ui/core/Chip";
import { makeStyles } from "@material-ui/core/styles";
import { emphasize } from "@material-ui/core/styles/colorManipulator";
const useChipStyles = makeStyles({
chip: {
color: ({ color }) => color,
backgroundColor: ({ backgroundColor }) => backgroundColor,
"&:hover, &:focus": {
backgroundColor: ({ hoverBackgroundColor, backgroundColor }) =>
hoverBackgroundColor
? hoverBackgroundColor
: emphasize(backgroundColor, 0.08)
},
"&:active": {
backgroundColor: ({ hoverBackgroundColor, backgroundColor }) =>
emphasize(
hoverBackgroundColor ? hoverBackgroundColor : backgroundColor,
0.12
)
}
}
});
const CustomChip = ({
color,
backgroundColor,
hoverBackgroundColor,
...rest
}) => {
const classes = useChipStyles({
color,
backgroundColor,
hoverBackgroundColor
});
return <Chip className={classes.chip} {...rest} />;
};
export default CustomChip;
下面是一个代码沙盒,演示了这一点:
这似乎效果很好。不幸的是,我使用的React版本不支持挂钩。希望我们能很快到达那里。同时,我提出了一个解决方案,使用HOC将使用道具的样式注入到组件中。以下是v4的Material UI将需要挂钩支持,因此为了继续获得进一步的Material UI增强,您一定要升级React。只要您已经在React 16上,而不是更早的版本,它应该是一个相当轻松的升级。