我正在包装 Material UI 的 Chip
组件,这样我就可以为 colors
属性传入“primary”和“secondary”以外的值。如果芯片是可点击的,我还想保持悬停效果,以便当光标悬停在芯片上时,芯片会转换为不同的颜色。颜色作为 Prop 传入,因此设置 backgroundColor
和 color
非常容易:
<Chip
style={{
backgroundColor: props.backgroundColor,
color: props.color
}}
/>
但是,由于我还想将悬停颜色作为 Prop 传递,因此我需要执行以下操作:
<Chip
style={{
backgroundColor: props.backgroundColor,
color: props.color,
'&:hover': {
backgroundColor: props.hoverBackgroundColor,
color: props.hoverColor
}
}}
/>
但是,&:hover
(据我所知)不能在 style
属性中使用。通常,&:hover
将在传递给 withStyles
的样式对象内部使用,但我无法从那里访问 Prop 。有什么建议吗?
最佳答案
您可以通过创建自己的自定义芯片组件来实现这一点。为了能够使用 Prop 来控制造型,你可以使用 makeStyles
. makeStyles
函数返回一个钩子(Hook),该钩子(Hook)可以接受一个对象参数来为您的样式提供变量。
这是一个可能的 CustomChip 实现:
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;
样式方法(包括使用 emphasize
函数生成悬停颜色和事件颜色)基于内部用于 Chip
的方法.
然后可以这样使用:
<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");
}}
/>
这是一个演示这个的 CodeSandbox:
这是示例的 Material-UI v5 版本:
import Chip from "@material-ui/core/Chip";
import { styled } from "@material-ui/core/styles";
import { emphasize } from "@material-ui/core/styles";
import { shouldForwardProp } from "@material-ui/system";
function customShouldForwardProp(prop) {
return (
prop !== "color" &&
prop !== "backgroundColor" &&
prop !== "hoverBackgroundColor" &&
shouldForwardProp(prop)
);
}
const CustomChip = styled(Chip, { shouldForwardProp: customShouldForwardProp })(
({ color, backgroundColor, hoverBackgroundColor }) => ({
color: color,
backgroundColor: backgroundColor,
"&:hover, &:focus": {
backgroundColor: hoverBackgroundColor
? hoverBackgroundColor
: emphasize(backgroundColor, 0.08)
},
"&:active": {
backgroundColor: emphasize(
hoverBackgroundColor ? hoverBackgroundColor : backgroundColor,
0.12
)
}
})
);
export default CustomChip;
关于css - 使用 props 设置 '&:hover' background-color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55008320/