实现思路
- 使用
useRef
创建引用对象,每个输入框对应一个 ref
。
- 将
ref
绑定到对应的输入框元素上。
- 在提交表单时,通过
ref.current.value
获取输入框的值。
关键代码示例
import React, { useRef } from 'react';
const FormComponent = () => {
const input1Ref = useRef();
const input2Ref = useRef();
const handleSubmit = (e) => {
e.preventDefault();
const value1 = input1Ref.current.value;
const value2 = input2Ref.current.value;
// 处理提交逻辑,例如发送数据到服务器
console.log(`Value 1: ${value1}, Value 2: ${value2}`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={input1Ref} placeholder="输入框1" />
<input type="text" ref={input2Ref} placeholder="输入框2" />
<button type="submit">提交</button>
</form>
);
};
export default FormComponent;