繁体   English   中英

在 formik 组件之外处理 formik 表单

[英]Handle formik form outside of formik component

我有一个formik表格如下。 我可以在 formik 组件中提交表单。 但是我怎么能在 formik 组件之外提交它(在这个例子中的页脚按钮内)。

Formik 网址:点击这里

特别是,我如何在Formik组件之外访问这些值handleChange, values, handleSubmit, errors,isValid,touched, handleBlur, isSubmitting,

我是在react-native做的,但我想 react 的概念会有所帮助,特别是使用useRef等。在网上找到了几个使用 ref 的例子,但没有一个工作。

<View>
    <Formik
        onSubmit={async values => {
            this.handleSubmit(values);
            await new Promise(resolve => setTimeout(resolve, 1000));
            console.warn(values);
        }}
        validationSchema={validationSchema}>
        {({
        handleChange,
        values,
        handleSubmit,
        errors,
        isValid,
        touched,
        handleBlur,
        isSubmitting,
        }) => (
        <View>
            <Form>
                <Text>First Name</Text>
                <TextInput
                    name="first_name"
                    value={values.first_name}
                    onChangeText={handleChange('first_name')}
                />
                {errors.first_name ? (
                <Text>{errors.first_name}</Text>/>
                ) : (
                    <></>
                )}
                <Button onPress={handleSubmit}>
                    <Text>Submit</Text>
                </Button>
            </Form>
        </View>
        )}
    </Formik>
    <Footer>
        <Button>Submit</Button>
    </Footer>
</View>

在创建可重复使用的弹出窗口并在弹出模板中包含保存按钮并在弹出内容中包含 formik 表单时,我遇到了同样的问题(因此我无法将按钮放在表单中,因为页脚在任何弹出窗口中重复使用)。

我通过向表单中的提交按钮添加 ref 并用 css 隐藏按钮,然后在单击所需的提交按钮时实际触发对隐藏提交按钮的单击来解决它。

也许不是最干净的解决方案,但它对我有用。

这是一个基本示例

<Formik>
    ....
    <Field>
    <Field>
    ...
    <button type="submit" style={{display:"none"}}  ref={this.submitButton}/> 
</Formik>

<div className="ftr">
    <button onClick={() => this.submitButton.current.click()}>Save</button>
</div>

希望这可以帮助

暂无
暂无

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

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