如何在父组件中访问子组件的 formik 值?

  • 本文关键字:组件 formik 访问 reactjs formik
  • 更新时间 :
  • 英文 :


我在一个子组件中有一个窗体。提交后,我需要访问父组件中的一个表单字段值。我一点也不明白。我不能使用useFormik,因为我有<Formik />组件。我提到了很多,但我无法理解

Parent component:
import ChildForm from "./ChildForm";
import "./styles.css";
export default function App() {
return (
<div className="App">
<ChildForm />
Email Address: {/* firstName; child form's firstName value  */}
</div> );
}
Child component:
const ChildComponent = () => {
return (
<Formik
initialValues={{
firstName: "",
lastName: "",
email: "",
}}
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
}}
>
<Form>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="Jane" />
<label htmlFor="lastName">Last Name</label>
<Field id="lastName" name="lastName" placeholder="Doe" />
<label htmlFor="email">Email</label>
<Field
id="email"
name="email"
placeholder="jane@acme.com"
type="email"
/>
<button type="submit">Submit</button>
</Form>
</Formik>
);
};
A quick CodeSandBox to quick preview: https://codesandbox.io/s/romantic-nightingale-956xxv?file=/src/App.js:0-271

您可以这样做,只需将函数从父级传递到子级,并接受表单值作为参数

https://codesandbox.io/s/friendly-pascal-db2rbu?file=/src/App.js

最新更新