react如何获取input值
获取 React 中 input 值的常用方法
受控组件方式
通过 useState 绑定 value 和 onChange 事件,实时同步输入框的值到状态:
import { useState } from 'react';
function ControlledInput() {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
);
}
非受控组件方式
使用 useRef 直接访问 DOM 元素,适合需要手动触发获取值的场景:
import { useRef } from 'react';
function UncontrolledInput() {
const inputRef = useRef(null);
const handleClick = () => {
alert(inputRef.current.value);
};
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>获取值</button>
</>
);
}
表单提交时获取值
通过 onSubmit 事件结合 FormData 获取多个输入值:
function FormExample() {
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
console.log(formData.get('username')); // 通过 name 属性获取
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" />
<button type="submit">提交</button>
</form>
);
}
第三方库简化
使用如 react-hook-form 等库管理表单状态:

import { useForm } from 'react-hook-form';
function HookFormExample() {
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data.inputName); // 自动收集表单数据
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('inputName')} />
<button type="submit">提交</button>
</form>
);
}
方法选择建议
- 实时验证/反馈:优先使用受控组件。
- 性能敏感场景:非受控组件减少渲染次数。
- 复杂表单:考虑
react-hook-form或formik等库。






