[英]conditional slider with material-ui
I am trying to construct a single Slider component in React that will enable me to choose whether I want a slider with two values or one, and store them in the component state.我正在尝试在 React 中构建一个单独的 Slider 组件,这将使我能够选择是否需要一个具有两个值或一个值的滑块,并将它们存储在组件状态中。 The slider with two values works fine, but the slider with only a single value does not move, however, I can console.log() the correct values.
具有两个值的滑块工作正常,但只有一个值的滑块不会移动,但是,我可以使用 console.log() 获取正确的值。 What can I do to fix it?
我能做些什么来修复它?
import React from "react";
import Slider from "@material-ui/core/Slider";
export default function GameOptions() {
return (
<div className="screen">
<GameSlider values={1} max={50} />
<GameSlider values={2} max={50} />
</div>
);
}
function GameSlider(props) {
const [value, setValue] = React.useState([0, props.max]);
const handleChange = (event, newValue) => {
setValue(newValue);
console.log(newValue);
};
const getValue = () => {
if (props.values == 1) {
return value[1];
}
return value;
};
const getSliderType = () => {
if (props.values == 1) {
return "range-slider";
}
return "continuous-slider";
};
return (
<Slider
value={getValue()}
onChange={handleChange}
valueLabelDisplay="auto"
aria-labelledby={getSliderType()}
/>
);
}
When "continuous-slider" is in use, the value received by the handleChange
function will be a single numeric value, as opposed to a numeric array.使用“连续滑块”时,
handleChange
函数接收的值将是单个数值,而不是数值数组。 So your handleChange
function should treat it as that.所以你的
handleChange
函数应该这样对待它。
const handleChange = (event, newValue) => {
setValue((props.values == 1) ? [newValue, newValue] : newValue);
console.log(newValue);
};
Additionally I think your getSliderType
function should be the otherway.另外我认为你的
getSliderType
函数应该是另一种方式。
const getSliderType = () => {
return (props.values == 1) ? "continuous-slider" : "range-slider";
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.