问题
Is there a way to pass formik form values from a child component to a parent component and handle form submission in parent component only. I have a use case where I'm building a form for restaurant. The form will have many many fields. So I grouped them and created seperate smaller formik forms component. All the child components' validation schema (yup) are written there inside the child component.
Or if there is any another method to accomplish this task, please let me know.
class FirstChildForm extends Component {
constructor(props) {
super(props);
this.state = {
firstChildFormData: {}
}
}
render() {
return (
<Formik
initialValues={{ }}
validationSchema={{ }}
{props => {const {values} = props;
return(
<div>First Form</div>
)
}}
)
}
}
class SecondChildForm extends Component {
constructor(props) {
super(props);
this.state = {
secondChildFormData: {}
}
}
render() {
return (
<Formik
initialValues={{ }}
validationSchema={{ }}
{props => {const {values} = props;
return(
<div>Second Form</div>
)
}}
)
}
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {
firstFormData : '',
secondFormData : '',
},
}
}
handleSubmit = () => {
}
render() {
return (
<Formik
initialValues={{ }}
validationSchema={{ }}
{props => {const {values, isSubmitting} = props;
return(
<div className='finalform'>
<FirstChildForm />
<SecondChildForm />
<button onClick={this.handleSubmit}>
Submit</button>
</div>
)
}}
)
}
}
回答1:
by using props archive this.
Screen 1:
render(
<View>
<Screen2
onValueChange={() => {
this.setState({formProps: formProps});
}}
/>
<FormButton
formProps={this.state.formProps}
// @ts-ignore
onPress={formProps.handleSubmit}
// tslint:disable-next-line:no-duplicate-string
title={'checkout'}
/>
</View>
)
Screen 2:
if (onValueChange) {
onValueChange(formProps);
}
来源:https://stackoverflow.com/questions/59408716/how-to-pass-a-child-components-validated-data-as-a-formik-form-to-its-parent