如何通过在 react 中使用 react-hook-form 来获取 react-phone-input-2 值
how to do get react-phone-input-2 value by using react-hook-form in react
我在提交时获得了 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>
<ReactPhoneInput />
是一个外部控制组件,因此您应该在这里使用 RHF 的 <Controller />
组件。在文档中查看此 section 以获取更多信息。
<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"}
/>
)}
/>
我在提交时获得了 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>
<ReactPhoneInput />
是一个外部控制组件,因此您应该在这里使用 RHF 的 <Controller />
组件。在文档中查看此 section 以获取更多信息。
<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"}
/>
)}
/>