我有一个子Formik组件,我需要将数据传递给我的父组件。在子Formik组件中,我有两个按钮: 1.一个onSubmit按钮,提交表单并转到下一页,然后 2.一个onClick按钮,可返回到最后一页
当我提交表单并转到下一页时,一切正常并签出。但是,当我倒退到最后一页时,我通过控制台记录日志时,传递的数据(是数组[])将转换为某种类。
我将问题缩小到第二个按钮是onClick而不是onSubmit类型。如果我将第二个按钮的类型设置为“提交”类型的按钮,则它可以工作,但会在Formik组件中调用onSubmit事件。我也尝试这样做:
<Button type="submit" onClick={() => this.submitAction = 'b'}>Back</Button>
<Button type="submit" onClick={() => this.submitAction = 'a'}>Next</Button>
and
onSubmit={values => {
if (this.submitAction === 'a') {this.props.nextStep('post1', values)}
if (this.submitAction === 'b') {this.props.lastStep('post1', values)}
}}
但是,这种方法的问题是两个按钮事件都通过了validationschema事件,这不是我想要的。
这是我的完整代码:
class Post2 extends React.Component {
submitAction = undefined;
render() {
const { classes } = this.props;
return (
<div>
<Formik
initialValues={{ studyType: this.props.initValues.studyType }}
onSubmit={values => {
this.props.nextStep('post2', values)
}} //here is my onSubmit event that gets called when the form submits
render={({ values }) => (
<Form>
<div>
<FieldArray
name="studyType"
render={arrayHelpers => (
<div>
{studyTypes.map(index => (
<div key={index}>
<label>
<input
name="studyType"
type="checkbox"
value={index}
checked={values.studyType.includes(index)}
onChange={e => {
if (e.target.checked) arrayHelpers.push(index);
else {
const idx = values.studyType.indexOf(index);
arrayHelpers.remove(idx);
}
}}
/>
{index}
</label>
</div>
))}
</div>
)}
/>
<Button onClick={(value) => this.props.lastStep('post2', value)}>Back</Button> //here are my two buttons
<Button type="submit">Next</Button> //here are my two buttons
</div>
</Form>
)}
/>
</div>
);
}
}
class FormikStepper extends React.Component {
state = {
activeStep: 1,
post0: {
title: '',
description: '',
},
post1: {
category: [],
},
};
nextStep = (post, values) => {
this.setState({ activeStep: this.state.activeStep + 1, [post]: values })
} //next step function which is called from child component
lastStep = (post, values) => {
this.setState({ activeStep: this.state.activeStep - 1, [post]: values })
} //last step function which is called from child component