我在子组件中有一个表单。提交后,我需要访问父组件中的表单字段值之一。我根本搞不懂。我不能使用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发布于 2022-11-05 03:03:04
您可以这样做,只需将函数从父函数传递到子函数,并接受窗体值作为参数。
https://codesandbox.io/s/friendly-pascal-db2rbu?file=/src/App.js
https://stackoverflow.com/questions/74324671
复制相似问题