简体   繁体   English

使用 Material-UI 中的滑块动态处理滑块

[英]Handle Sliders dynamically using slider from Material-UI

I want to generate a sliders dynamically according to user input, and don't know how to save values on change.我想根据用户输入动态生成一个滑块,不知道如何在更改时保存值。 Following is the code given of my implementation.以下是我的实现给出的代码。 The problem is that I can't get value via event.target.value // priceCities is an array of objects:问题是我无法通过 event.target.value 获取价值 // priceCities 是一个对象数组:

handlePrices(priceCities){

        return   priceCities.map( (cstate, index) => (
             <li key={index}  >{cstate.name}  <Slider key={index} min={3} max={500}  step={1} style={{height: 100}} axis="y" 
            defaultValue={5}  id ={cstate.id} onChange={ this.handleSlider.bind(this,cstate.id )}  value={this.state.values[cstate.id] }   />   <span>{this.state.values[cstate.id]}</span> </li> 
        ));

}


this.state = {
    values: []
}

and onChange() method here:onChange()方法在这里:

   handleSlider ( event,i ) {

   // this.state.sliderValue[event.target.id] =  event.target.value;
    //console.log('handlerslider'+event.target.id+' '+event.target.value);
    let values = [...this.state.values];
    values[i] = event.target.value;
    this.setState({ values });
}

Finally I found solution by defining the onChange method like this :最后我通过定义这样的 onChange 方法找到了解决方案:

 onChange={(event,value) => this.handleSlider(event, value,currState.id )} 

and the code of handleSlider function :和 handleSlider 函数的代码:

handleSlider (event, value,id) {
    let values = [...this.state.sliderValue];

    values[id] =  value;
    this.setState({sliderValue: values });
    console.log('handlerslider'+value+' '+id);
}

2020 Answer with Hooks 2020 年带有钩子的答案

Something simple like this will work:像这样简单的事情会起作用:

 <Slider
   onChange={(_, value) =>
      setState(value)
   }
   step={1}
   min={1}
   max={50}
   value={value}
   valueLabelDisplay="auto"
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM