首页 > 解决方案 > 如何通过 ApolloClient 的变异提交 formik 表单?

问题描述

我已经使用 antd 创建了一个示例 Formik 表单。现在我正在使用 POST_MUTATION 添加突变。如何通过 formik 提交表单值。这里我在表单中调用了handleSubmit。但它没有被调用?

 import React from 'react'
import { Formik, Field, Form } from 'formik';
import * as AntD from "antd";
import TextField from "./shared/TextField"
import { Mutation, graphql } from 'react-apollo'
import gql from 'graphql-tag'
import data from './shared/data'

const POST_MUTATION = gql`
  mutation PostMutation($username: String!, $email: String!, $password: String!){
    post(username: $username, email: $email, password: $password) {

      username
      email
      password
    }
  }
`


class FormikApollo extends React.Component {
  state = {
      username: '',
      email: '',
      password: '',
      data: {}
  }

  handleChange= (e) => {
        this.setState({
            [e.target.name] : e.target.value,
            data
        })
  }

  handleSubmit = () => {
   alert("called")
  }

我用这种方式添加了我的formik表单。现在我想提交这些未提交的表单值。如何在formik中提交表单值?

form = props => {
            const { username, email, password  } = this.state;
            return (
                <div align="center">
                    <h3 align="center">Registration Form</h3>
                    <Mutation mutation={POST_MUTATION} variables={{ username, email, password }}>
                    { postMutation  => (
                    <Form onSubmit={(formikValues) => postMutation({ variables: formikValues })}>
                        <Row gutter={4}>
                            <Col span={12} push={5}>
                                <Field
                                    name="username"
                                    label="Name"
                                    placeholder="Enter a Name"
                                    component={TextField}
                                    formitemlayout={formItemLayout} 
                                    value={this.state.username}
                                    onChange={this.handleChange}
                                    />

                                <Field
                                    name="email"
                                    label="Email"
                                    placeholder="Enter an Email"
                                    component={TextField}
                                    formitemlayout={formItemLayout} 
                                    value={this.state.email}
                                    onChange={this.handleChange}
                                    />

                                <Field
                                    name="password"
                                    label="Password"
                                    type="password"
                                    placeholder="Enter a Password"
                                    component={TextField}
                                    formitemlayout={formItemLayout} 
                                    value={this.state.password}
                                    onChange={this.handleChange}
                                  />


                                 <Button type="submit" onClick={JSON.stringify(postMutation)}>Submit</Button>


                            </Col>
                        </Row>
                    </Form>
                    )}

                    </Mutation>
                </div>
            )
        }


        render() {

            return (
                <div align="center">
                    <Formik
                        initialValues = {{
                          username: '',
                          email:'',
                          password:''
                        }}
                        render={this.form}
                    />

                </div>
            )
        }

    }

    export default FormikApollo

标签: reactjsgatsbyantdapollo-clientformik

解决方案


你的方法是正确的。最好将整个组件包装成突变并使用它来渲染道具。这是一个简单的寄存器组件。如果您发现某些语法难以理解,我正在使用打字稿。

ant-design 和 graphql(Typescript) 的工作示例:https://github.com/benawad/graphql-typescript-stripe-example

优酷系列:https://www.youtube.com/watch?v=G-Kj8Re6spA&list=PLN3n1USn4xllF5t1GZhEwFQNDnStgupdB

import { Field, Formik } from "formik";
import React from "react";
import Layout from "../components/Layout";

import { RegisterMutationVariables, RegisterMutation } from "../../schemaTypes";

const registerMutation = gql`
  mutation RegisterMutation($email: String!, $password: String!) {
    register(email: $email, password: $password)
  }
`;

export default () => {
  return (
    <Layout title="Register page">
      <Mutation<RegisterMutation, RegisterMutationVariables>
        mutation={registerMutation}
      >
        {register => (
          <Formik
            validateOnBlur={false}
            validateOnChange={false}
            onSubmit={async (data, { setErrors }) => {
              try {
                const response = await register({
                  variables: {
                    data
                  }
                });
                console.log(response);
              } catch (err) {
                console.log(err)
              }
            }}
            initialValues={{
              email: "",
              password: ""
            }}
          >
            {({ handleSubmit }) => (
              <form onSubmit={handleSubmit}>
                <Field
                  name="email"
                  placeholder="email"
                  component={InputField}
                />
                <Field
                  name="password"
                  placeholder="password"
                  type="password"
                  component={InputField}
                />
                <button type="submit">submit</button>
              </form>
            )}
          </Formik>
        )}
      </Mutation>
    </Layout>
  );
};

推荐阅读