我想创建一个通用的useInput
挂钩,该挂钩带有对输入DOM的引用。在提交表单时,我会使用useInput
组件中Form
的引用来获取所有输入值。
输入的DOM值更改时,我很难理解如何实现useRef
来获取值。到目前为止,它所做的只是继续记录undefined
作为参考...
我尝试过的事情:
const useInput = ({ label, name }, ref) => {
const [value, setValue] = useState('');
const inputRef = useRef();
useEffect(() => {
const { current } = inputRef;
console.log(current); // logs undefined - shouldn't it refer to the input dom?
}, [value])
const input = (
<Form label={label}>
<input name={name} onChange={e => setValue(e.target.value)} ref={inputRef}/>
</Form>
)
return [value, input];
};
export default useInput;
答案 0 :(得分:0)
我成功了-我忘了在inputRef.current
内更新useEffect
,因为值状态发生了变化-不确定这是否是最佳做法...
const useInput = ({ label, name }, ref) => {
const [value, setValue] = useState('');
const inputRef = useRef();
useEffect(() => {
inputRef.current = value // *added this line, so it updates the ref as state changes.
}, [value])
const input = (
<Form label={label}>
<input name={name} onChange={e => setValue(e.target.value)} ref={inputRef}/>
</Form>
)
return [value, input, inputRef]; // also added inputRef as an output so I can consume it
};
export default useInput;