gpt4 book ai didi

reactjs - 如何将react-hook-form与ant design或material UI一起使用

转载 作者:行者123 更新时间:2023-12-03 13:22:53 25 4
gpt4 key购买 nike

我正在尝试使用react-hook-form库来验证表单。当我使用 ant design 或 Material UI 渲染 View 时,它无法正常工作。

<Input name="firstName" ref={register({ required: true })} />
{errors.firstName && 'First name is required'}

发生了一些警告:“缺少名称......”

最佳答案

对于 Material-UI,您可以通过 TextField 组件 prop inputRef 传递 register (我也使用 Yup 进行验证模式)

import React, { useState } from 'react';
import { Button, TextField } from '@material-ui/core';
import useForm from 'react-hook-form';
import { object, string } from 'yup';

const Form: React.FC = () => {
const schema = object().shape({
username: string().required('Username is required'),
password: string().required('Password is required'),
});
const { register, handleSubmit, errors } = useForm({ validationSchema: schema });
const onSubmit = (data: any) => {
console.log(data);
};

return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="username"
error={!!errors.username}
label="Username"
helperText={errors.username ? errors.username.message : ''}
type="email"
inputRef={register}
fullWidth
/>
<TextField
name="password"
error={!!errors.password}
label="Password"
inputRef={register}
helperText={errors.password ? errors.password.message : ''}
type="password"
fullWidth
/>

<Button
color="primary"
type="submit"
variant="contained"
fullWidth
>
Submit
</Button>
</form>
);
};

关于reactjs - 如何将react-hook-form与ant design或material UI一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58833574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com