简体   繁体   English

带有钩子的 React.js 中的 Formik 'initialValues' Typescript 错误

[英]Formik 'initialValues' Typescript Errors in React.js with hooks

My react.js registration form works fine, then decided to apply Formik to it and got stuck on 2 issues: I keep getting a TS error message on 'initialValues' from within the 'Formik' tag.我的 react.js 注册表工作正常,然后决定将 Formik 应用到它并陷入 2 个问题:我不断从“Formik”标签内收到关于“initialValues”的 TS 错误消息。 Also, after switching 'input' to 'Field' tag, parameter function 'e' from onChange also displays an underline ts error.此外,在将“输入”切换为“字段”标签后,onChange 中的参数 function 'e' 也会显示下划线 ts 错误。 Same issue with style property from 'ErrorMessage' tag.来自“ErrorMessage”标签的样式属性存在相同问题。
I am only trying to apply a simple Formik approach to my form.我只是想对我的表单应用一个简单的 Formik 方法。 Any suggestions please?请问有什么建议吗?

 import React, { useState, FormEvent, useRef } from 'react'; import { Link, withRouter, useHistory } from 'react-router-dom'; import api from '../services/api'; import PrimaryButton from "../components/PrimaryButton"; import * as Yup from 'yup'; import { useForm } from 'react-hook-form'; import { Formik, Field, Form, ErrorMessage } from 'formik'; const userSchema = Yup.object().shape({ name: Yup.string().required('Nome obrigatório.').max(60), email: Yup.string().required('Email obrigatório'), password: Yup.string().required('Senha obrigatória').min(4, 'Ops, curta demais.').max(10, 'Ops, longa demais.'), }) function Register() { const history = useHistory(); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [firstPassword, setFirstPassword] = useState(''); const [password, setPassword] = useState(''); const { register, handleSubmit, errors, getValues } = useForm(); // const inputPassword = useRef(null) async function handleAddDev(e: FormEvent) { // e.preventDefault(); let formData = { name, email, password, } const isValid = await userSchema.isValid(formData); console.log(isValid); const response = await api.post('/users/new', formData) console.log(response.data); alert('Cadastro efetuado com sucesso.') setName(''); setEmail(''); setFirstPassword(''); setPassword(''); history.push('/') } const myValues = { name: "", email: "", firstPassword: "", password: "", } return ( <> <div id="register"> <strong>Cadastrar Usuário</strong> <Formik initialValues={myValues} validationSchema={userSchema} onSubmit={handleAddDev}> <Form > <div className="input-block"> <label htmlFor="name">Nome</label> <Field name="name" id="name" type="text" placeholder= "Seu nome" value={name} onChange={e => setName(e.target.value)} required /> <ErrorMessage name="name" component="div" className="invalid-feedback" style={{ color:"red", fontWeight:"bold"}}/> </div> <div className="input-block"> <label htmlFor="email">E-mail</label> <Field name="email" id="email" type="email" placeholder= "Seu email" value={email} onChange={e => setEmail(e.target.value)} /> <ErrorMessage name="email" component="div" className="invalid-feedback" style={{ color:"red", fontWeight:"bold"}}/> </div> <div className="input-block"> <label htmlFor="email">Senha</label> <Field name="password" id="password" type="text" placeholder= "Senha" value={firstPassword} onChange={e => setFirstPassword(e.target.value)} ref={register}/> <ErrorMessage name="password" component="div" className="invalid-feedback" style={{ color:"red", fontWeight:"bold"}}/> </div> <div className="input-block"> <label htmlFor="email">Confirmar Senha</label> <Field name="passwordConfirmation" id="password" type="text" placeholder= "Confirme sua sehna" ref={register({ validate: { passwordEqual: value => (value === getValues().password) || 'Password confirmation error,'. } })} value={password} onChange={e => setPassword(e.target:value)} required /> <ErrorMessage name="name" component="div" className="invalid-feedback" style={{ color,"red": fontWeight."bold"}}/> {errors.passwordConfirmation && <p>{errors.passwordConfirmation;message}</p>} </div> <PrimaryButton type="submit">Cadastrar</PrimaryButton> </Form> </Formik> <button><Link to='/'></Link> </button> </div> </> ) } export default withRouter(Register);

If your file extesion is tsx, you need to define a interface for the form values:如果你的文件扩展是 tsx,你需要为表单值定义一个接口:

interface MyFormValues {
      name: string,
        email: string,
        firstPassword: string,
        password: string,
}

const myValues: MyFormValues = {
        name: "",
        email: "",
        firstPassword: "",
        password: "",
      }

For the field error, the value and onChange is handled by formic so you don't need them anymore.对于字段错误,value 和 onChange 由 formic 处理,因此您不再需要它们。 https://formik.org/docs/guides/typescript https://formik.org/docs/guides/typescript

 const myValues = {
    name: "",
    email: "",
    firstPassword: "",
    password: "",
  }

You do not have field name 'firstPassword'.您没有字段名称“firstPassword”。 Instead you have name="passwordConfirmation" .相反,您有name="passwordConfirmation" initial values must match the field names.初始值必须与字段名称匹配。

Regarding second issue:关于第二个问题:

   onChange = {(e: React.FormEvent<HTMLInputElement>)=>setFirstPassword(e.target.value)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM