簡體   English   中英

使用 Material-UI 中的滑塊動態處理滑塊

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

我想根據用戶輸入動態生成一個滑塊,不知道如何在更改時保存值。 以下是我的實現給出的代碼。 問題是我無法通過 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: []
}

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 });
}

最后我通過定義這樣的 onChange 方法找到了解決方案:

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

和 handleSlider 函數的代碼:

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

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

2020 年帶有鈎子的答案

像這樣簡單的事情會起作用:

 <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