[英]setState not working inside onChange function
I am trying to found out why this works我试图找出为什么这有效
const Navigation:React.FC = () =>{
const [Volume, setVolume] = useState<number>(50)
const onChange = (event) => {
setVolume(event.target.value);
}
return(
<>
<Slider label="Slider label" value={Volume} onChange={(event) => onChange(event)} max='100' min='0'/>
</>
)
}
export default Navigation
But this does not work但这不起作用
const Navigation:React.FC = () =>{
const [Volume, setVolume] = useState<number>(50)
return(
<>
<Slider label="Slider label" value={Volume} onChange={(event: ChangeEvent<HTMLElement>) => setVolume(event.target.value)} max='100' min='0'/>
</>
)
}
export default Navigation
It is giving this error Property 'value' does not exist on type 'EventTarget & HTMLElement'
它给出了这个错误Property 'value' does not exist on type 'EventTarget & HTMLElement'
I would like to use the second one because it makes my code a lot shorter and cleaner.我想使用第二个,因为它使我的代码更短更清晰。
any idea why or how I could make the second one work知道为什么或如何使第二个起作用
Thank for the help感谢您的帮助
If I'm correct in assuming that this is a Typescript
error, then you need the provide proper type
for the event, there is no value
property in the HTMLElement type, you need to use HTMLInputElement for the slider.如果我假设这是Typescript
错误是正确的,那么您需要为事件提供正确的type
,HTMLElement 类型中没有value
属性,您需要为 slider 使用 HTMLInputElement。
const onChange = (event:React.ChangeEvent<HTMLInputElement>) => {
setVolume(parseInt(event.target.value));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.