formik 相关问题

React的表单库

Formik 不会更新状态给定的值

我正在使用 Metronic React Template 并自定义表单。我的一些表单字段的值被保存在一个状态中。当我提交带有填充输入的表单时,这些值将作为空字符串返回...

回答 1 投票 0

React 测试库:输入字段未更新测试中的值

我正在使用一个自定义 React 组件,该组件将 Office UI Fabric TextField 包装在 Formik 表单中。尽管遵循使用 React 和 Formik 处理输入字段的典型模式,但我

回答 1 投票 0

如何使用 Yup 正确验证步进器

我有一个关于如何使用 Yup 正确验证步骤表单的问题。 我有以下案例: const schema = Yup.object().shape({ 步骤1:Yup.object().shape({ 来源:Yup.string().req...

回答 1 投票 0

如何在Typescript中正确使用useField(Formik)?

当我尝试从我的传递所有道具(类型、占位符、类名等)时出现错误,我该如何修复它? ** 这是我的代码:** 当我尝试从我的<MyTextInput />传递所有道具(类型、占位符、类名等)时出现错误,我该如何修复它? ** 这是我的代码:** <MyTextInput label="Password:" name="password" placeholder="Enter your password" className="text-pink-600" /> 这是我的自定义输入组件: import { FieldHookConfig, useField } from 'formik'; import React from 'react'; interface IFieldProps { label?: string; } const MyTextInput: React.FC<IFieldProps & FieldHookConfig<string>> = ({ label, ...props }) => { const { name } = props; const [field, meta] = useField(props); // console.log({ field, meta, others }); return ( <div className="flex flex-col"> <label htmlFor={name}>{label}</label> <input id={name} type="text" {...field} {...props} /> // error here... </div> ); }; export default MyTextInput; ** 这是错误:** Type '{ ref?: LegacyRef<HTMLInputElement> | undefined; key?: Key | null | undefined; accept?: string | undefined; alt?: string | undefined; autoComplete?: HTMLInputAutoCompleteAttribute | undefined; ... 295 more ...; innerRef?: ((instance: any) => void) | undefined; } | { ...; } | { ...; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'. Type '{ ref?: LegacyRef<HTMLSelectElement> | undefined; key?: Key | null | undefined; autoComplete?: string | undefined; disabled?: boolean | undefined; ... 275 more ...; checked?: boolean | undefined; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'. Type '{ ref?: LegacyRef<HTMLSelectElement> | undefined; key?: Key | null | undefined; autoComplete?: string | undefined; disabled?: boolean | undefined; ... 275 more ...; checked?: boolean | undefined; }' is not assignable to type 'ClassAttributes<HTMLInputElement>'. Types of property 'ref' are incompatible. Type 'LegacyRef<HTMLSelectElement> | undefined' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'. Type '(instance: HTMLSelectElement | null) => void' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'. Type '(instance: HTMLSelectElement | null) => void' is not assignable to type '(instance: HTMLInputElement | null) => void'. Types of parameters 'instance' and 'instance' are incompatible. Type 'HTMLInputElement | null' is not assignable to type 'HTMLSelectElement | null'. Type 'HTMLInputElement' is missing the following properties from type 'HTMLSelectElement': length, options, selectedIndex, selectedOptions, and 4 more.ts(2322) (property) JSX.IntrinsicElements.input: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> 我不想这样做:<input {...field} placeholder={props.placeholder} type={props.type} /> 我认为问题源于FieldHookConfig的定义: export type FieldHookConfig<T> = GenericFieldHTMLAttributes & FieldConfig<T>; 其中 GenericFieldHTMLAttributes 定义为 export type GenericFieldHTMLAttributes = | JSX.IntrinsicElements['input'] | JSX.IntrinsicElements['select'] | JSX.IntrinsicElements['textarea']; 基本上,TypeScript 会警告您,由于您使用的是 FieldHookConfig,因此您收到的属性总是有可能是 select 或 textarea 属性,这些属性与 input 不兼容。 我认为解决这个问题的最好方法是: import { FieldConfig, useField } from 'formik'; import React from 'react'; interface IFieldProps { label?: string; } const MyTextInput: React.FC<IFieldProps & FieldConfig<string> & JSX.IntrinsicElements['input']> = ({ label, ...props }) => { const { name } = props; const [field, meta] = useField(props); // console.log({ field, meta, others }); return ( <div className="flex flex-col"> <label htmlFor={name}>{label}</label> <input id={name} type="text" {...field} {...props} /> </div> ); }; export default MyTextInput; this should 将类型缩小为仅访问 input 属性。

回答 1 投票 0

如何修复 Yup(react-hook-form)(reactjs-typescript) 中的“没有重载与此调用匹配”错误

const schema = Yup.object({ logo_image_name: Yup.string().required('徽标图像名称为必填项。'), favicon: Yup.string().required('需要favicon。'), logo_type:是的。mi...

回答 1 投票 0

对象可能为“null”:TypeScript、React useRef 和 Formik innerRef

在我使用 Formik 的 React/TypeScript 应用程序中,我收到错误 对象可能为“空”。 TS2531 125 | 125 > 126 | 在我使用 Formik 的 React/TypeScript 应用程序中,我收到错误 Object is possibly 'null'. TS2531 125 | <Modal.Footer> > 126 | <Button variant="primary" type="submit" form="nicknameForm" disabled={!(formRef.current.isValid && formRef.current.dirty)}>Apply</Button> | ^ 127 | </Modal.Footer> 128 | </Modal> 129 | ) 尝试将 formRef.current.isValid 更改为 formRef!.current.isValid 并将 formRef.current.dirty 更改为 formRef!.current.dirty,但错误仍然存在。 为什么会这样,我们该如何修复这个错误?谢谢! import React, { useState, useEffect, useRef } from 'react'; import { Button, Modal, Form } from 'react-bootstrap'; import { Formik } from 'formik'; interface IModal { show: boolean; handleClose: () => void; } export function NicknameModal({show, handleClose}: IModal) { const formRef = useRef(null); return ( <Modal show={show} onHide={handleClose}> <Modal.Header closeButton> <Modal.Title>My Title</Modal.Title> </Modal.Header> <Modal.Body> <Formik initialValues={{ nickname: '', }} innerRef={formRef} onSubmit={( values, { setSubmitting } ) => { setSubmitting(true); handleClose(); setSubmitting(false); }} > {({values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, setFieldValue }) => ( <Form id="nicknameForm" onSubmit={handleSubmit}> <Form.Group controlId="formNickname"> <Form.Label>Nickname</Form.Label> <Form.Control type="text" name="nickname" onChange={handleChange} onBlur={handleBlur} value={values.nickname} /> </Form.Group> </Form> )} </Formik> </Modal.Body> <Modal.Footer> <Button variant="primary" type="submit" disabled={!(formRef.current.isValid && formRef.current.dirty)} form="nicknameForm">Apply</Button> </Modal.Footer> </Modal> ) } 更新: 如果将 const formRef = useRef(null); 更改为 const formRef = useRef();,我们现在会遇到不同的错误: Type 'MutableRefObject<undefined>' is not assignable to type '((instance: FormikProps<{ nickname: string; }> | null) => void) & MutableRefObject<undefined>'. Type 'MutableRefObject<undefined>' is not assignable to type '(instance: FormikProps<{ nickname: string; }> | null) => void'. Type 'MutableRefObject<undefined>' provides no match for the signature '(instance: FormikProps<{ nickname: string; }> | null): void'. TS2322 71 | nickName: '', 72 | }} > 73 | innerRef={formRef} | ^ 74 | onSubmit={( 75 | values: Values, 76 | { setSubmitting }: FormikHelpers<Values> 您需要设置 useRef 的类型,其中 FormValues 是您的表单值 type FormValues = {}; useRef<FormikProps<FormValues>>(null); https://github.com/formium/formik/issues/2600#issuecomment-693479057 尝试: import { FormikProps } from "formik"; const formRef = useRef<FormikProps<any>>(null); 首先,您需要为Formik初始值定义一个类型: interface HelpFormInitialValues { destination_city: string; cell_phone: string; } const initialValues: FormnameInitialValues = { cell_phone: "", destination_city: "", }; 然后为 ref 状态定义一个表单类型,并将表单初始值类型设置为它: import { FormikProps } from "formik"; const formikRef = useRef<FormikProps<HelpFormInitialValues>>(null); 现在您可以在 Formik 状态下使用 ref 的所有属性,而不会出现任何 typescript 错误,并且还可以获得自动完成的好处。 if (formikRef.current) formikRef.current.resetForm(); if (formikRef.current) formikRef.current.isValid();

回答 3 投票 0

如何在nextJs中访问服务器上的表单值?

我无法正确地将表单数据传递到 nextJS 中的 api 端点。我正在使用 formik 和 yup 来创建表单并验证数据。当我将数据记录到客户端的控制台时,我看到用户处于...

回答 1 投票 0

如何将 DropdownPicker setValue 与 Formik handleChange 或 setValueField 一起使用?

如何将下拉选择器 setValue 与 Formik 一起使用? handleChange 或 setValueField 无法正常工作。有什么建议么? const [打开,setOpen] = useState(false); 常量项 = [ { 标签:'...

回答 2 投票 0

如何在卸载组件时防止吐司?

我试图阻止组件卸载时,如果用户单击提交。尝试使用 useState 进行操作,但它对我不起作用。 我的目标是向用户展示 toast,但如果他点击提交,他应该...

回答 1 投票 0

使用 Formik 时出现“未捕获(承诺)类型错误:无法获取”

我正在学习如何使用Formik。我正在尝试访问通过 Postman 工作的后端,但我似乎无法使用 Formik 进行获取。 这是我的 onSubmit 的 App.js 代码: 我正在学习如何使用 Formik。我正在尝试访问通过 Postman 工作的后端,但我似乎无法使用 Formik 获取。 这是我的 onSubmit 的 App.js 代码: <Formik initialValues={{ ...initialState, }} validationSchema={formValidation} onSubmit={values => fetch('/api/client', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(values), }).then(res => res.json())}> 这是我的按钮组件代码: const ButtonWrapper = ({ children, ...otherProps }) => { const { submitForm } = useFormikContext(); const handleSubmit = () => { submitForm(); }; const configButton = { variant: 'contained', color: 'primary', fullWidth: true, onClick: handleSubmit }; return ( <Button {...configButton} > {children} </Button> ); }; export default ButtonWrapper; 不确定我做错了什么 TypeError: Failed to fetch表示网络请求不成功。尝试打开浏览器的开发人员工具并选择“网络”选项卡。查看 React 发出的请求是否与您在 Postman 中发出的请求相匹配。另请检查开发人员控制台选项卡,因为它应该记录导致请求失败的确切错误。 浏览器在网络请求中执行其他检查,其中之一是响应标头和 CORS 或跨源请求脚本。如果 Access-Control-Allow-Origin 响应标头与本地主机站点不匹配,那么您将收到此错误。

回答 1 投票 0

ReactJS 中的 Material UI 自动完成类别

我正在使用 MUI 自动完成和 Formik,我想将其分组。如果它没有 sub_accounts,那么它不应该有标题标签。像这样的东西:https://mui.com/material-ui/...

回答 1 投票 0

如何在 React + Symfony 6 后端表单中链接两个表?

我有一个带有 Symfony 6.4 后端的 React Form,我正在尝试将两个表链接在一起(Tiers 和 GroupeDdo),其中每个 Tiers 有一个 GroupeDdo。这是我的 Tiers.php : 我有一个带有 Symfony 6.4 后端的 React Form,我试图将两个表链接在一起(Tiers 和 GroupeDdo),其中每个 Tiers 有一个 GroupeDdo。这是我的 Tiers.php : <?php namespace App\Entity; use App\Repository\TiersRepository; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: TiersRepository::class)] class Tiers { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\ManyToOne(inversedBy: 'tiers')] private ?GroupeDdo $groupe_ddo = null; [...] public function getId(): ?int { return $this->id; } public function getGroupeDdo(): ?GroupeDdo { return $this->groupe_ddo; } public function setGroupeDdo(?GroupeDdo $groupe_ddo): self { $this->groupe_ddo = $groupe_ddo; return $this; } } 这是我的 GroupeDdo.php : <?php namespace App\Entity; use App\Repository\GroupeDdoRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: GroupeDdoRepository::class)] class GroupeDdo { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column(length: 255)] private ?string $groupe_ddo_nom = null; #[ORM\OneToMany(targetEntity: Ddo::class, mappedBy: 'groupe_ddo')] private Collection $ddos; #[ORM\OneToMany(targetEntity: Tiers::class, mappedBy: 'groupe_ddo')] private Collection $tiers; #[ORM\OneToMany(targetEntity: User::class, mappedBy: 'groupe_ddo')] private Collection $users; public function __construct() { $this->ddos = new ArrayCollection(); $this->tiers = new ArrayCollection(); $this->users = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getGroupeDdoNom(): ?string { return $this->groupe_ddo_nom; } public function setGroupeDdoNom(string $groupe_ddo_nom): static { $this->groupe_ddo_nom = $groupe_ddo_nom; return $this; } /** * @return Collection<int, Ddo> */ public function getDdos(): Collection { return $this->ddos; } public function addDdo(Ddo $ddo): static { if (!$this->ddos->contains($ddo)) { $this->ddos->add($ddo); $ddo->setGroupeDdoId($this); } return $this; } public function removeDdo(Ddo $ddo): static { if ($this->ddos->removeElement($ddo)) { // set the owning side to null (unless already changed) if ($ddo->getGroupeDdoId() === $this) { $ddo->setGroupeDdoId(null); } } return $this; } /** * @return Collection<int, Tiers> */ public function getTiers(): Collection { return $this->tiers; } public function addTier(Tiers $tier): static { if (!$this->tiers->contains($tier)) { $this->tiers->add($tier); $tier->setGroupeDdoId($this); } return $this; } public function removeTier(Tiers $tier): static { if ($this->tiers->removeElement($tier)) { // set the owning side to null (unless already changed) if ($tier->getGroupeDdoId() === $this) { $tier->setGroupeDdoId(null); } } } } 这是我的表格的完整版本: import React, { useState, useEffect } from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import { useAuth } from '../context/AuthContext'; import Cookies from 'js-cookie'; // L'interface Tiers définit les champs de la table Tiers et leur types interface Tiers { tiers_raison_sociale: string | null; tiers_intitule: string | null; tiers_heures_ouverture: { [key: string]: { ouverture: string; fermeture: string }[]; } | null; tiers_telephone: string | null; tiers_courriel: string | null; tiers_rdv: boolean | null; groupe_ddo_id: number | null; tiers_adresse: string | null; tiers_ville: string | null; tiers_cp: string | null; tiers_pays: string | null; } // L'interface GroupeDDo définit les champs de la table GroupeDdo et leur types interface GroupeDDO { id: number; groupeDdoNom: string; } const TiersForm: React.FC = () => { //Utilisation d'un useState de l'API const [apiError, setApiError] = useState(''); const [groupeDDOList, setGroupeDDOList] = useState<GroupeDDO[]>([]); const [selectedGroupeId, setSelectedGroupeId] = useState<number | null>(0); const { isAuthenticated } = useAuth(); if (!isAuthenticated) { window.location.href = '/'; } useEffect(() => { const fetchGroupeDDOList = async () => { try { const response = await fetch('http://127.0.0.1:8000/api/liste-groupe-ddo'); if (!response.ok) { throw new Error('Erreur lors de la récupération des données des groupes'); } const data = await response.json(); setGroupeDDOList(data); } catch (error) { console.error(error); } }; fetchGroupeDDOList(); }, []); //Valeur initiales du formulaire const initialValues: Tiers = { tiers_raison_sociale: '', tiers_intitule: '', tiers_heures_ouverture: { lundi: [{ ouverture: '', fermeture: '' }], mardi: [{ ouverture: '', fermeture: '' }], mercredi: [{ ouverture: '', fermeture: '' }], jeudi: [{ ouverture: '', fermeture: '' }], vendredi: [{ ouverture: '', fermeture: '' }], samedi: [{ ouverture: '', fermeture: '' }], dimanche: [{ ouverture: '', fermeture: '' }], }, tiers_telephone: '', tiers_courriel: '', tiers_rdv: false, groupe_ddo_id: null, tiers_adresse: '', tiers_ville: '', tiers_cp: '', tiers_pays: '', }; const onSubmit = async (values: Tiers) => { try { if (!isAuthenticated) { throw new Error('Vous devez être connecté pour effectuer cette action'); } const token = Cookies.get('authToken'); const selectedGroupe = groupeDDOList.find(groupe => groupe.id === (selectedGroupeId as number)); if (!selectedGroupe) { throw new Error('Le groupe selectionné est introuvable'); } if (selectedGroupe) { values.groupe_ddo_id = selectedGroupe.id; } const response = await fetch('http://127.0.0.1:8000/api/create/tiers', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify(values), }); if (!response.ok) { throw new Error('Erreur lors de la création de la société'); } // Réinitialiser les champs du formulaire après la soumission réussie setApiError(''); window.location.href = '/'; } catch (error) { setApiError('Impossible d\'envoyer le formulaire'); } }; // Conditions de chaque champ du formulaire const validate = (values: Tiers) => { const errors: Partial<Tiers> = {}; // Si le code de société n'est pas entré, écrire qu'il est requis if (!values.tiers_raison_sociale) { errors.tiers_raison_sociale = 'Raison sociale de la société requise'; } return errors; }; return ( <> {groupeDDOList.length === 0 ? ( <p>Chargement en cours...</p> ) : ( <Formik {...{ initialValues, onSubmit, validate }} > {({ isSubmitting, values, handleChange }) => ( <Form> <fieldset> <legend>A Quel Groupe de Société doit-il être lié ?</legend> <Field as="select" name="groupe_ddo_id" label="Groupe Société d'un tiers" value={selectedGroupeId} onChange={(e: React.ChangeEvent<HTMLSelectElement>) => { // const selectedValue = (e.target as HTMLSelectElement).value; const selectedValue = parseInt(e.target.value); // const selectedGroupe = selectedGroupeId ? groupeDDOList.find(groupe => groupe.id === parseInt(selectedValue)) : null; // if (selectedGroupe) { setSelectedGroupeId(selectedValue); // } }}> {groupeDDOList.map((groupe, index) => ( <option key={index} value={groupe.id}> {groupe.groupeDdoNom} </option> ))} </Field> <ErrorMessage name="id" component="div" className="error" /> {apiError && <div className="error">{apiError}</div>} <br /> <button type="submit" disabled={isSubmitting}> {isSubmitting ? 'Création en cours...' : 'Créer Tiers'} </button> </fieldset> </Form> )} </Formik > )} </> ); }; export default TiersForm; 这里的问题是,当我尝试获取 GroupeDdo 列表以创建选择字段时,我看不到它们,并显示错误:警告:未定义的数组键“groupe_ddo_id”。我应该怎么做才能获取我所有的 GroupeDdo 并确保它是数据库中 GroupeDdo 的值? 谢谢! 来自我的控制器,我使用 findAll 函数来获取所有内容。但在这样做的过程中,我也试图获取集合,这不是我想要的,因为其中一个集合是 Tiers,这正是我试图使用表单创建的。 因此,我创建了一个函数,仅从 GroupeDdo 实体获取我需要的内容。

回答 1 投票 0

ReactJS 中的 Material UI 自动完成子选择

我正在使用 MUI 自动完成和 Formik,我想将其分组。如果它没有 sub_accounts,那么它不应该有标题标签。像这样的东西:https://mui.com/material-ui/...

回答 1 投票 0

使用 Formik 和 Yup 库为 React + vite 创建可重用的表单组件

我正在尝试创建一个react+vite项目,我试图使用Formik和Yup实现可重用的表单组件,但还无法实现这一点。 我创建了一个名为 <

回答 1 投票 0

是否可以对react-admin库创建的表单使用Formik验证?

我是新手,刚刚开始在我的一个项目中使用react-admin 库。我找不到任何地方使用 formik 和反应管理表单。那么是否可以通过react-admin使用formik验证...

回答 1 投票 0

如何使用useformik resetForm或handleReset函数重置formik中的单选按钮?

我有一个表单,我希望在成功提交后清除我的输入,useFormik handleReset 或 useformik.resetForm() 在文本类型输入上工作正常,但单选按钮仍然保持选中状态...

回答 1 投票 0

Formik 值未保存在 redux 持久切片中

店铺: 从“@reduxjs/toolkit”导入{configureStore}; //切片 从“./mainLayoutSlice”导入mainLayoutReducer; 从“./userDataSlice”导入userDataReducer; 我...

回答 1 投票 0

聆听Formik价值观的变化

我在组件中有一个 formik 表单,我想重用它。为了做到这一点,我需要监听表单值的变化,以便调用两个函数 getFormValues 和 getFormErrors,这将是

回答 3 投票 0

React Typescript:如何处理 Formik 文件上传?

我正在 React Typescript 上使用 Formik 来处理我的学生资料表单。该表单用于处理简历和成绩单文件上传。我注意到一切都很好,直到我测试了我的...

回答 2 投票 0

将新定义的 props 传递给作为 props 传递的(功能)组件

假设我有一个如下所示的父组件: 假设我有一个如下所示的父组件: <ParentComponent contentComponent={ <GenericContent content={<FormContent title="Content Title" formComponent={<ChildComponent />} />} /> } /> 现在,在我的 FormContent 组件中,我想将 props 传递给我的 formComponent,在本例中是 ChildComponent,但实际上可以是另一个组件。 但是我知道我想要传递的 props 总是在 formComponent 组件中。 const FormContent = ({ title, formComponent, }: FormContentPropsType) => ( <> <Formik enableReinitialize validateOnChange={false} initialValues={{ ...formData, }} validationSchema={SandboxFormValidationSchema} onSubmit={sendForm} > {({ values, setValues, errors, setErrors, handleSubmit, }) => ( <Form> {/* Here I would like to use formComponent with the following props : formData={values} setFormData={setValues} formErrors={errors} setFormErrors={setErrors} handleSubmit={handleSubmit} */} </Form> )} </Formik> </> 我怎样才能实现这个目标? 根据我对你的问题的理解,你想向子组件添加额外的道具。 这可以使用 React.cloneElement() 来实现 <Form> React.cloneElement(fromComponent,{ formData={values} setFormData={setValues} formErrors={errors} setFormErrors={setErrors} handleSubmit={handleSubmit} }) </Form> React.cloneElement() 将元素(组件)、新的 props 和孩子作为参数。

回答 1 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.