gpt4 book ai didi

reactjs - 如何使用 Formik 应用突变?

转载 作者:行者123 更新时间:2023-12-03 13:30:52 25 4
gpt4 key购买 nike

我一直在尝试想出一种方法来实现 react-apollo 的提交功能<Mutation>成分。发现了一些对于这个简单任务来说似乎有点过分的例子,包括 thisthis 。由于我是一名刚刚开始学习 React 的新程序员,更不用说 Formik 甚至 HOC(我想这就是要走的路?),我无法真正理解这些示例以及如何使它们适应我的类似物 Hello world代码。

这是我的注册表单:

import React, { Component } from "react";
import { withFormik, Form, Field } from "formik";
import { Mutation } from "react-apollo";
import { gql } from "apollo-boost";

const CREATE_USER_MUTATION = gql`
mutation CREATE_USER_MUTATION(
$name: String!
$email: String!
$password: String!
) {
signup(name: $name, email: $email, password: $password) {
id
name
email
password
permissions
}
}
`;

class App extends Component {
state = {
name: "",
email: "",
password: ""
};
render() {
return (
<Mutation mutation={CREATE_USER_MUTATION}>
{(signup,{loading}) => (
<Form>
<Field type="text" name="name" placeholder="Name" />
<Field type="email" name="email" placeholder="Email" />
<Field type="password" name="password" placeholder="Password" />
<button type="submit" disabled={loading}>
Sign Up
</button>
</Form>
)}
</Mutation>
);
}
}

const SignupPage = withFormik({
mapPropsToValues() {
return {
name: "",
email: "",
password: ""
};
},
handleSubmit() { ... }
})(App);

export default SignupPage;

如何访问signuphandleSubmit

最佳答案

使用<Formik />将是一个更好的方法,而不是使用 withFormik() HOC。

<Formik />在里面<Mutation/> (而不是相反)您可以在 onSubmit 字段中调用您的突变。

https://jaredpalmer.com/formik/docs/api/formik

<Mutation mutation={CREATE_USER_MUTATION}>
{(signup,{loading}) => (

<Formik
initialValues={{ name: '', email: '', password: '' }}
onSubmit={ async (values, actions) => {
// You can access the signup mutation in here now
// You can access values.name, values.email, values.password
// You can access actions, e.g. actions.setSubmitting(false) once you've finished the mutation
}}


render={props => (

<Form onSubmit={props.handleSubmit}>
<Field
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.name}
name="name"
placeholder="Name"
/>
<Field
type="email"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.email}
name="email"
placeholder="Email"
/>
<Field
type="password"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.email}
name="password"
placeholder="Password"
/>
<button type="submit" disabled={loading}> Sign Up </button>
</Form>
)}
/>
)}
</Mutation>

关于reactjs - 如何使用 Formik 应用突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55126259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com