我当前使用的React DatePicker有一个 onChange 属性,可以让您跟踪所选日期
<DatePicker
selected={startDate}
startDate={startDate}
endDate={endDate}
onChange={e => setValue(e)}
/>
当我以直接的方式使用 useState() 钩子时,它工作得非常好:
const [value, setValue] = useState()
但是,我需要在自定义 Hook 中使用它来组合各种变量。该onChange()
属性无法在该设置中工作。没有错误,只是没有交互。
例如,我将自定义 Hook 定义如下,并onChange()
像以前一样从属性调用,没有任何反应:
const useCustomHook = () => {
const [value, setValue] = useState()
return [value, () => setValue()]
}
const [value, setValue] = useCustomHook()
这可能是因为 setter 没有接收任何参数,因此没有更新状态的值。
尝试以这种方式返回钩子:
const useCustomHook = () => {
const [value, setValue] = useState()
return [value, (val) => setValue(val)]
}
或者干脆setValue
直接传递:
const useCustomHook = () => {
const [value, setValue] = useState()
return [value, setValue]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句