如何将道具从反应 class 传递给 formik?

How to pass props from react class to formik?

我正在尝试将一些道具从 React class 传递到我的功能组件 formik,然后我想添加一些回调函数以将这些数据返回到已更改的文本上。但不确定我该如何完成。请检查我的以下代码:

这是我的Main.jsxclass

// 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;

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

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

相反,您必须使用 Routerender 道具并将道具直接传递到组件中。这应该将 username 传递到 mapPropsToValues:

<Route exact path="/" render={() => <RegisterAccount username={this.state.username} />} />