Material-UI: 如何获取Slider中的值?

Material-UI: How to get the value in Slider?

我正在使用 Material-UI Slider 并且我想通过 onChange 函数获取值。

我的代码是这样的:

const SliderScale: React.FC = () => {
  const classes = useStyles();
  const [inputValue, setInputValue] = useState(0);

  const updateRange = (value: number) : void => {
    setInputValue(value);
  };


  return (
    <div className={classes.root}>
      <Typography id="discrete-slider" gutterBottom>
        value
      </Typography>
      <Slider
        defaultValue={0}
        value={inputValue}
        getAriaValueText={valuetext}
        aria-labelledby="discrete-slider"
        valueLabelDisplay="on"
        step={0.5}
        marks={false}
        min={0}
        max={10}
        onChange={updateRange}
      />
    </div>
  );
};

export default SliderScale;

这不起作用并显示此错误。

(JSX attribute) onChange?: ((event: React.ChangeEvent<{}>, value: number | number[]) => void) | undefined No overload matches this call. Overload 1 of 2, '(props: { component: ElementType; } & { 'aria-label'?: string | undefined; 'aria-labelledby'?: string | undefined; 'aria-valuetext'?: string | undefined; color?: "primary" | "secondary" | undefined; ... 18 more ...; valueLabelFormat?: string | ... 1 more ... | undefined; } & CommonProps<...> & Pick<...>): Element', gave the following error. Type '(value: number) => void' is not assignable to type '(event: ChangeEvent<{}>, value: number | number[]) => void'. Types of parameters 'value' and 'event' are incompatible. Type 'ChangeEvent<{}>' is not assignable to type 'number'. Overload 2 of 2, '(props: DefaultComponentProps<SliderTypeMap<{}, "span">>): Element', gave the following error.

有人知道怎么弄吗?

来自 docsonChange 签名是:

function(event: object, value: number | number[]) => void

新值在第二个参数中,而不是 onChange 回调中的第一个参数。将您的代码更改为:

<Slider {...props} onChange={(_, value) => setInputValue(value)} />

您需要将 updateRange 函数更改为如下内容:

const updateRange  = (event: React.ChangeEvent<{}>, newValue: number | number[]) => {
    setInputValue(newValue as number[]);
}