Material-UI -拇指在范围滑块中的切换样式



我有两个实体要在Material-UISlider上显示为拇指组件,我需要为每个拇指组件设置不同的样式。

实体A的拇指出现在白色圆圈中,实体B的拇指出现在红色圆圈中。我通过使用数据索引

部分实现了此功能。
if (data-index === 0) {
//show white circle
} else {
//show red circle
}

然而,这有一个很大的缺陷,即如果我滑动实体B并使其站在实体A之前,那么实体B就会变成白色圆圈,因为实体B的数据索引变成了0。除了使用data-index,还有没有其他方法可以保持样式,而不管它们在滑块上的位置。

这是沙箱。

import * as React from "react";
import PropTypes from "prop-types";
import Slider, { SliderThumb } from "@material-ui/core/Slider";
import { styled } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import clsx from "clsx";
const EntitySlider = styled(Slider)(({ theme }) => ({
color: "#3a8589",
height: 3,
padding: "13px 0",
"& .MuiSlider-thumb": {
height: 27,
width: 27,
backgroundColor: "#fff",
border: "1px solid currentColor",
"&.second-thumb": {
backgroundColor: "red"
},
"&:hover": {
boxShadow: "0 0 0 8px rgba(58, 133, 137, 0.16)"
}
},
"& .MuiSlider-track": {
height: 3
},
"& .MuiSlider-rail": {
color: theme.palette.mode === "dark" ? "#bfbfbf" : "#d8d8d8",
opacity: theme.palette.mode === "dark" ? undefined : 1,
height: 3
}
}));
function ThumbComponent(props) {
const { children, className, ...other } = props;
const extraClassName =
other["data-index"] === 0 ? "first-thumb" : "second-thumb";
return (
<SliderThumb {...other} className={clsx(className, extraClassName)}>
{children}
</SliderThumb>
);
}
ThumbComponent.propTypes = {
children: PropTypes.node
};
export default function CustomizedSlider() {
return (
<Box sx={{ width: 320 }}>
<Typography gutterBottom>Airbnb</Typography>
<EntitySlider
components={{ Thumb: ThumbComponent }}
getAriaLabel={(index) =>
index === 0 ? "Minimum price" : "Maximum price"
}
defaultValue={[20, 40]}
/>
</Box>
);
}

除了使用data-index之外,是否还有其他方法可以保持样式,而不管它们在滑块上的位置

你的样式像预期的那样工作,唯一意想不到的事情是当你拖动白色拇指通过红色拇指时,红色拇指开始被拖动,白色拇指停止,因为MUISlider不允许左拇指移动通过右拇指。你可以从源代码中看到,值数组总是被排序,Slider将从当前值中找到最接近的拇指索引设置为活动:

{/* white thumb on the left, red thumb on the right */}
<Slider value={[0, 100]} {...} />
{/* white thumb still on the left, red thumb still on the right */}
<Slider value={[100, 0]} {...} />

所以,是的,拇指的样式是一致的,只是拇指的位置被限制在其他拇指和最小/最大值之间。

参考

  • https://mui.com/components/slider/最小距离

最新更新