范围滑块的值发生变化,但滑块不移动



我在使用库react输入范围(或任何其他滑块(时遇到了问题:我可以看到console.log(value(时值正在正确更改,但移动滑块时滑块不会移动……无论是否通过道具。

知道吗?

import React from 'react';
import InputRange from 'react-input-range';
interface Props {
min:number;
max:number;
step?:number;
value:any;
id:string;
}
const RangeSlider = ({ min, max, step=1, value, id }: Props) => {

function onValueChange(newval: any){
console.log(newval);
value=newval;
//some other actions here
}

return (
<div className="slider m-4 mb-6">
<InputRange
minValue={min}
maxValue={max}
step={step}
onChange={onValueChange}
value={value}
/>
</div>
);
};
export default RangeSlider;

必须使用State才能执行此操作。

const [value,setValue] = React.useState(value);
function onValueChange(newval: any){
setValue(newval)
}

与使用状态相比,我认为这可能是React的props的问题。在上找到https://kentcdodds.com/blog/props-vs-state,道具更改时DOM不会更新,因此滑块不会移动。

正如react输入范围的官方文档所建议的那样,您应该使用state来更新和读取值。

您的RangeSlider没有扩展React.Component,所以您不能使用state。当然,我不知道你为什么不使用这样的东西

class RangeSlider extends React.Component {

我建议您使用一个扩展React.Component的类,然后使用state作为值。然后,您可以设置值更改时的状态,如下所示(取自react输入范围的文档:

onChange={value => this.setState({ value })}

有关将道具传递到组件的正确教程,请访问https://www.robinwieruch.de/react-pass-props-to-component.

或者,如另一个答案所示,您当然可以使用useState钩子。(https://reactjs.org/docs/hooks-state.html)。这样就不必扩展React的组件了

我希望,这会有所帮助。

相关内容

最新更新