您可以通过创建自己的定制芯片组件来实现这一点。为了能够使用props来控制样式,您可以使用makeStyles
. 该makeStyles
函数返回一个钩子,它可以接受一个对象参数,为您的样式提供变量。
这是一个可能的 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;