如何将道具从React类传递给Formik?

时间:2019-06-13 02:14:09

标签: reactjs formik yup

我试图将一些道具从React类传递到我的功能组件formik,然后我想添加一些回调函数以使这些数据在文本更改后返回。但不确定如何才能做到这一点。请检查我的以下代码:

这是我的Main.jsx类

// Some imports were removed to keep everything looks cleaner
import RegisterAccount from "RegisterAccount.jsx";

class Main extends React.Compoenent {

     constructor(props) {
          super(props);

          this.state = {
             username: "This is username value..."
          }
     }

    render() {
        return (
            <Container fluid>
              <Switch>
                <Route exact path="/register" component={RegisterAccount} data={this.state.username} />
              </Switch>
            </Container>
        )
    }
}

export default Main;

这是我的RegisterAccount.jsx

// Some imports were removed to keep everything looks cleaner
import { Form as FormikForm, Field, withFormik } from "formik";
import * as Yup from "yup";

const App = ({ values, errors, touched }) => (
  <FormikForm className="register-form  " action="">
    <h3 className="register-title">Register</h3>
    <Form.Group className="register-form-group">
      <Field
        name="username"
        type="text"
        placeholder="USERNAME"
        className="form-control rounded register-form-control"
      />
      {touched.username && errors.username && <p>{errors.username}</p>}
    </Form.Group>
  </FormikForm>
);

const FormikApp = withFormik({
  mapPropsToValues({ username, email, password, confirmPassword }) {
    return {
      username: username || ""
    };
  },
validationSchema: Yup.object().shape({
    username: Yup.string()
      .min(6)
      .max(32)
      .required()
      .test("username", "error message of username", async value => {
        return true;
      })
})(App);


export default FormikApp;

1 个答案:

答案 0 :(得分:1)

您看到的问题似乎不是来自Formik,而是来自React Router。您的Route不会像您使用data那样传递道具:

<Route exact path="/register" component={RegisterAccount} data={this.state.username} />

相反,您必须使用Route的{​​{1}}属性并将属性直接传递到组件中。这应该将render传递到username中:

mapPropsToValues