简体   繁体   中英

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:

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:

   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={(event,value) => this.handleSlider(event, value,currState.id )} 

and the code of handleSlider function :

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

Something simple like this will work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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