gpt4 book ai didi

reactjs - 从子 React Reactive Form 更新父状态变量

转载 作者:行者123 更新时间:2023-12-03 19:05:42 25 4
gpt4 key购买 nike

我正在尝试探索react next 的图书馆框架。因为我是 angular开发人员,我喜欢重复使用我的一些 reactive-form到我的新应用程序。我找到了this库,因为它具有几乎相同的 reactive-form 实现.
现在,我正在使用 state我的父表格上的变量;但是,每当我尝试从子项(这是 react 形式)更新值时。我无法完成它。
这是我复制它的简单代码。

import React, { useState } from "react";
import { FieldGroup, FieldControl } from "react-reactive-form";

export default function App() {
const [isRegistered, setIsRegistered] = useState(false);

async function submitForm(e) {
e.preventDefault();
setIsRegistered(state => !state);
console.log(isRegistered);
//await function call .....
}

return (
<div>
<h1>Hello StackBlitz!</h1>
<FieldGroup
control={form}
render={({ get, invalid }) => (
<form onSubmit={submitForm}>
<FieldControl
name="email"
render={TextInput}
meta={{ label: "Email" }}
/>
<button type="submit">Submit</button>
<p>{isRegistered.toString()}</p>
{isRegistered ? <span>Registered Successfully</span> : null}
</form>
)}
/>

</div>
)
}
为了简短起见, formTextInput只是一个模型和一个元素。
如您所见,我正在更新 submitForm 上的状态变量通过将其作为 onSubmit 来发挥作用我的表格的功能;但是,我可以触发 submitForm每当我尝试提交时,但 state variable值不变。
问题是,当我尝试调用 submitForm child 之外的函数(FieldGroup),我能够更新值。
我创建了一个 sample app所以你也可以检查。

最佳答案

看来你需要设置strict支持 false对于 FieldGroup ,如此处所述:https://github.com/bietkul/react-reactive-form/blob/master/docs/api/FieldGroup.md

strict: boolean;

Default value: true

If true then it'll only re-render the component only when any change happens in the form group control irrespective of the parent component(state and props) changes.

关于reactjs - 从子 React Reactive Form 更新父状态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63669442/

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