在TypeScript React中用useRef获取表单值却返回HTML标签的问题
问题:useRef获取表单时返回HTML标签而非输入值
你将useRef绑定在了<form>标签上,所以ref.current返回的是整个form的DOM元素,而非输入框的值。以下是几种解决方式:
方法1:直接使用已维护的useState状态(推荐)
你已经通过handleInput将输入框的值同步到了input状态中,提交时直接使用该状态即可,无需额外借助ref:
const submitTodoName = (event: FormEvent<HTMLFormElement>): void => { event.preventDefault(); dispatch(addTodoName(input)); console.log(input); // 此处为输入框的值 dispatch(toggleNaming(false)); }
方法2:将ref绑定到输入框上
若一定要用ref获取输入值,需把ref绑定在<input>标签而非form上:
// 定义输入框的ref const inputRef = useRef<HTMLInputElement>(null); // 提交时获取输入值 const submitTodoName = (event: FormEvent<HTMLFormElement>): void => { event.preventDefault(); if (inputRef.current) { const inputValue = inputRef.current.value; dispatch(addTodoName(inputValue)); console.log(inputValue); } dispatch(toggleNaming(false)); } // 在input标签上绑定ref <input type='text' name="input" className='p-1 rounded bg-light border-0 ms-4' style={{ width: '15vw' }} onChange={handleInput} ref={inputRef} ></input>
方法3:通过form元素的elements属性获取输入值
如果坚持使用form的ref,可通过form的elements属性定位内部输入框:
const submitTodoName = (event: FormEvent<HTMLFormElement>): void => { event.preventDefault(); if (ref.current) { const inputElement = ref.current.elements.namedItem('input') as HTMLInputElement; const inputValue = inputElement.value; dispatch(addTodoName(inputValue)); console.log(inputValue); } dispatch(toggleNaming(false)); }
内容的提问来源于stack exchange,提问作者lgab1219
相关产品推荐
相关产品推荐

