所以我试图在React中使用Material UI滑块。但问题是,当我使用OnChange
时,每次值改变时都会触发该函数。我只想让它在鼠标左键向上时触发。然后我意识到有一个功能:
callOnChangeCommitted
:https://mui.com/material-ui/api/slider/
现在的问题是球不再滑动了。只与OnChange
球以前滑动,但现在球只有在我放开鼠标按钮时才会移动。这是我现在使用它的方式:
// In the render/return
<Slider
defaultValue={defaultValue}
value={parseFloat(sliderValue)}
step={0.1}
marks={marks}
valueLabelDisplay="on"
onChangeCommitted={sliderChange}
sx={{color: theme.palette.secondary.main}}
//onChange={sliderChange}
// I could not find a way to detect left mouse button up to make an
// if(leftMouseButton == up) { make API call }
// else { //do nothing }
/>
// The function
const sliderChange = (event, newValue) => {
console.log("new slider value: " + newValue)
setSliderValue(newValue);
axios.get(uri + "/" + newValue, { headers: auth }).then((res) => {
setObjectsEtcEtc(res.data);
})
};
(我的)解决方案:
看了一段时间后,确实有一种方法可以抓住鼠标。
<Slider
defaultValue={defaultValue}
value={parseFloat(sliderValue)}
step={0.1}
marks={marks}
valueLabelDisplay="auto"
sx={{ color: cimTheme.palette.secondary.main }}
onChange={sliderChange} // change slider value + slider value state and nothing else
onMouseUp={() => {
commitSliderValue(); //commit slider value when mouse up
}}
/>
onChange
和onChangeCommitted
的论证中都有一个事件。但不同之处在于,onChange
只捕获mosedown
和mousemove
事件,而onChangeCommitted
只在触发mouseup
事件时运行。
所以你可以像这样混合使用这些函数:
<Slider
defaultValue={defaultValue}
value={parseFloat(sliderValue)}
step={0.1}
marks={marks}
valueLabelDisplay="on"
onChangeCommitted={handleChangeCommited}
onChange={handleChange}
sx={{ color: theme.palette.secondary.main }}
/>;
//call api when mouse is up
const handleChangeCommited = (
event: React.SyntheticEvent | Event,
newValue: number | Array<number>
) => {
axios.get(uri + "/" + (newValue as number), { headers: auth }).then((res) => {
setObjectsEtcEtc(res.data);
});
};
// change the value when mouse is down or moving
const handleChange = (event: Event, newValue: number | number[]) => {
setSliderValue(newValue as number);
};