首页 > 解决方案 > 如何通过在 react 中使用 react-hook-form 来获取 react-phone-input-2 值

问题描述

我在提交时获得 TextField 值,但不是 ReactPhoneInput 值,如何使用 react-hook-form 获取值

import ReactPhoneInput from "react-phone-input-2"
import {TextField,Button}from "@material-ui/core"

const {register, handleSubmit,formState: { errors }} = useForm()

const getData= (data) => {
   console.log(data.username)
   console.log(data.username);
}

形式

<form onSubmit={handleSubmit(getData)} >

  <TextField {...register("username")} />

   <ReactPhoneInput
      inputExtraProps={{
        name: "phone",
        required: true,
        autoFocus: true
      }}

      country={"in"}
       onlyCountries={["in"]}                     
       countryCodeEditable={false}
        specialLabel={"Player Mobile Number"}
       rules={{ required: true }}
     />
<Button type='submit>Submit</Button> 
</form>

标签: reactjsreact-hook-form

解决方案


<ReactPhoneInput />是一个外部控制组件,因此您应该<Controller />在这里使用 RHF 的组件。查看文档中的此部分以获取更多信息。

<Controller
  control={control}
  name="phone"
  rules={{ required: true }}
  render={({ field: { ref, ...field } }) => (
    <ReactPhoneInput
      {...field}
      inputExtraProps={{
        ref,
        required: true,
        autoFocus: true
      }}
      country={"in"}
      onlyCountries={["in"]}
      countryCodeEditable={false}
      specialLabel={"Player Mobile Number"}
    />
  )}
/>

编辑 React Hook 表单 - react-phone-input-2


推荐阅读