【问题标题】:react-hook-form How can I pass field value to a parent componentreact-hook-form 如何将字段值传递给父组件
【发布时间】: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);

Edit code here

【问题讨论】:

  • 您想要的JSX 应该是这样的:&lt;Form /&gt;&lt;WatchedField/&gt; 或者您希望在Form 中包含&lt;WatchedField/&gt;,但在WatchedField 正文中调用useWatch 而不是From

标签: reactjs react-redux react-hooks react-hook-form


【解决方案1】:

useForm() 放入父组件中,然后将其作为道具传递给子组件

import React from "react";
import ReactDOM from "react-dom";
import { useForm, useWatch } from "react-hook-form";

import "./styles.css";

function Form({ form }) {
  const { register, handleSubmit } = form;
  return (
    <>
      <form onSubmit={handleSubmit((data) => console.log("data", data))}>
        <label>Name:</label>
        <input ref={register} name="name" />
      </form>
    </>
  );
}
function App() {
  const form = useForm();
  const { control } = form
  const name = useWatch({ control, name: "name" })
  return (
    <>
      <h1>{name}</h1>
      <Form form={form} />
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

或者,您也可以在子组件中使用useFormContext(),而无需传递任何道具。 useFormContext() 钩子将从父级或最近祖先的useForm() 获取上下文。

import React from "react";
import ReactDOM from "react-dom";
import { useForm, useWatch, useFormContext } from "react-hook-form";

import "./styles.css";

function Form() {
  const { register, handleSubmit } = useFormContext();
  return (
    <>
      <form onSubmit={handleSubmit((data) => console.log("data", data))}>
        <label>Name:</label>
        <input ref={register} name="name" />
      </form>
    </>
  );
}
function App() {
  const { control } = useForm();
  const name = useWatch({ control, name: "name" })
  return (
    <>
      <h1>{name}</h1>
      <Form />
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2021-04-29
    • 2020-07-27
    • 2020-04-25
    • 2020-01-09
    相关资源
    最近更新 更多