【发布时间】:2022-01-05 16:50:19
【问题描述】:
我想获取 react-hook-form 组件内的字段值并将其打印到表单外。 该值应更新 onChange。有没有办法在表单组件之外使用 useWatch?
import React from "react";
import ReactDOM from "react-dom";
import { useForm, useWatch } from "react-hook-form";
import "./styles.css";
function Form() {
const { register, control, handleSubmit } = useForm();
return (
<>
<form onSubmit={handleSubmit((data) => console.log("data", data))}>
<label>Name:</label>
<input ref={register} name="name" />
<p>{useWatch({ control, name: "name" })}</p>
</form>
</>
);
}
function App() {
return (
<>
<h1>The Value of the input should goes here</h1>
<Form />
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
【问题讨论】:
-
您想要的
JSX应该是这样的:<Form /><WatchedField/>或者您希望在Form中包含<WatchedField/>,但在WatchedField正文中调用useWatch而不是From?
标签: reactjs react-redux react-hooks react-hook-form