简体   繁体   English

在 React 中使用 formik 将数据从一个组件传递到另一个组件

[英]Passing data from one component to another in React using formik

I've created a simple react component for a form with few input fields using formik.我使用 formik 为具有很少输入字段的表单创建了一个简单的反应组件。 My form is rendered three times on my home page for three different type of users, but I only have one button that is outside the component and on click it should save the data inside the PersonalInformation component.我的表单在我的主页上为三种不同类型的用户呈现三次,但我只有一个位于组件外部的按钮,单击它应该将数据保存在PersonalInformation组件中。 This is how my code looks inside my App.js (ignore the users and data for now):这是我的代码在 App.js 中的外观(暂时忽略用户数据):

{users.map((data, i) => { return <PersonalInformation key={i} /> })}
<Button>Submit</Button> //this is the button that needs to save the data inside of PersonalInfo component od click

My question is how I can save the data inside the three forms on click on the button?我的问题是如何在单击按钮时将数据保存在三个表单中? In end-point on the back end I would like to get an array of three objects, each objects will contain info about each field in the form.在后端的端点中,我想获得一个包含三个对象的数组,每个对象将包含有关表单中每个字段的信息。 I guess what I need is to pass data from PersonalInformation component to onClick() event in Button , but I am not sure how to do that with formik.我想我需要的是将数据从PersonalInformation组件传递到Button onClick()事件,但我不确定如何使用 formik 来做到这一点。

if you don't use any state management, context etc i think simplest way is you can pass reference to your save method upper.如果您不使用任何状态管理、上下文等,我认为最简单的方法是您可以将引用传递给您的保存方法上层。

import React, {useRef} from "react";
import PersonalInformation from "./PersonalInformation";
import "./styles.css";

export default function App() {
  const saveRef = useRef(null)
  return (
    <div className="App">
      <PersonalInformation passSave={(ref) => saveRef.current = ref}/>
      <button onClick={() => saveRef.current()}> save </button>
    </div>
  );
}

//---------------------------------------------------------

import React, { useCallback, useEffect, useRef } from "react";

const PersonalInformation = ({passSave}) => {
    const formInput = useRef(null);
    const save = useCallback(() => {
      console.log(formInput.current.value)
    }, [formInput])

    useEffect(()=>{
      passSave(save)
    }, [passSave, save])

    return (
      <input type="text" ref={formInput} />
    )
}

export default PersonalInformation;

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

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