要使用 ref 获取到 input 标签中的值,首先需要创建一个 ref 对象并将其绑定到 input 标签上。然后,可以通过访问 ref 对象的 value 属性来获取标签中的值。
下面是一个示例代码:
import React, { useRef } from 'react';
function App() {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
console.log(inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">提交</button>
</form>
);
}
export default App;
在这个示例中,我们创建了一个 ref 对象 inputRef
,并将其绑定到 input 标签上。然后,在表单的 onSubmit 事件处理函数中,我们可以通过访问 inputRef.current.value
来获取输入框的值。