javascript - 如何使用滑块 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>
解决方案
您可以将您的类型更新为对象类型以存储键值对。例如:
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});
不丢失其他键值对
推荐阅读
- python - 从python中的html中提取href链接
- android - AndroidJUnit4 :- GrantPermissionRule 无法允许单元测试的运行时权限?
- mumps - 做bonmin的时候怎么做腮腺炎
- microsoft-teams - 微软团队获取来电号码
- php - 如何使用 Laravel 收银员进行客户订阅(活动和取消)?
- angular - Angular Project 在运行 yarn start 时出现以下错误
- java - 如果应用程序运行超过约 8 小时,则奇怪的 android 系统行为
- r - 根据二分网络边列表中的公共顶点创建新边列表
- json - 我在 JSON 文件中嵌套了数据,并且正在使用嵌套结构。如何快速访问嵌套在第一个结构中的值
- javascript - javascript下载按钮而不是右键单击