首页 > 解决方案 > 如何使用滑块 Material UI ReactJS 中的键存储新的更新值

问题描述

如下代码所示,我存储状态,并且在使用onChange={(...)=>setValue1(...)}, value.target.ariaValueText.
我的动机是我想将它与{key}中提到的相关联<Form.Lable>,以便我可以将更新的值与键一起存储。

 const [value, setValue1] = React.useState(1);
 const handleChange=(changeEvent)=>{
 setValue1(prevState => {...prevState, [key]:changeEvent.target.value});
//console.log(key);
 console.log(prevState.key);
};

 return <div className={classes.root}>
        <Form.Label> {key} </Form.Label>
        <Slider
          
          defaultValue={dict[key]}
          aria-labelledby="discrete-slider-custom"
          getAriaValueText={valuetext}
          valueLabelDisplay="auto"
          //getAriaValueText={valuetext}
          //value={dict[key]}
          step={0.01}
          min={min1}
          max={max1}

          //onChange={} // for example updating a state value
          //onChangeCommitted={} // for example fetching new data

          //marks={marks_arr[i]}
         
          //onChange={handleChange}
          onChange={(changeEvent) =>
             setValue1(changeEvent.target.value)
          }
        
        />
       </div>
    })
    }
    </Form.Group>

标签: javascriptreactjs

解决方案


您可以将您的类型更新为对象类型以存储键值对。例如:

 const [value, setValue1] = React.useState({});

 ...


 setValue1({[key]: changeEvent.target.value});
 // ---------^ this will create/update attribute with value of "key" in your state

如果您有多个滑块,则必须执行类似的操作

setValue1(prevState => {...prevState, [key]: changeEvent.target.value});

不丢失其他键值对


推荐阅读