如何从 React Select 访问值并将它们传递给提交时的 Formik 值?

How to access values from React Select and pass them to Formik values on Submit?

我想访问我的 React-Select 元素值并将其作为值传递到 OnSubmit 函数中并添加到从 formik 收集的值中。

我在 Formik 中创建了一个多元素表单。我在模态中访问此表单。在表单中,我访问表单元素 username, email, password 的值就好了。 Code Below:

  handleSubmit = (values,) => {
    const { onSuccess } = this.props;
    console.log(values);
    onSuccess(values);
  };

我还有一个 React-Select 组件,我用 labelvalue 对加载了一些数据。

我想将 selected 值添加到来自 fomrik 的值列表中。下面的回复只给了我这个信息。

  selectOnChangeCallback = response => {
    // eslint-disable-next-line no-console
    console.log('selectOnChangeCallback', response);
  };

还有我的 React select 组件:

                  <ReactSelect
                    isMulti={false}
                    options={selectData}
                    onChangeCallback={this.selectOnChangeCallback}
                  />

我在 Modal 中使用这个函数访问它:

  closeCreateUserModal = response => {
    this.setState({ isCreateUserModalOpen: false });
    // eslint-disable-next-line
    this.props.notify({
      message: `User ${response.username} was added to group `,
      status: STATUS.success,
    });

    console.log(response)

    return this.sampleGet();
  };

我的表单组件:

const UserValidationSchema = Yup.object().shape({
  username: Yup.string('Provide a Username').required('Username is Required'),
  email: Yup.string().email('Provide a Valid email Address'),
  password: Yup.string('Provide a Password').required('Password s required'),
  confirmPassword: Yup.string('Provide your password again')
    .required('Password Confirmation is Required')
    .oneOf([Yup.ref('password')], 'Passwords do not match')
});

const INITAIL_VALUES = {
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  group: {}
};

class ViewUser extends Component {
  static propTypes = {
    ...formPropTypes,
    username: PropTypes.string,
    email: PropTypes.string,
    password: PropTypes.string,
    confirmPassword: PropTypes.string,
    groupSelect: PropTypes.func,
    onSuccess: PropTypes.func
  };

  static defaultProps = {
    email: ''
  };

  state = {
    type: 'password',
    groups: []
  };

  componentDidMount() {
    this.fetchListGroups();
  }

  fetchListGroups = () => {
    listGroups().then(({ data }) => {
      this.setState({ groups: data });
    });
  };

  mapListGroupToSelect = () => {
    const { groups } = this.state;
    return groups.map(group => ({
      label: group.name,
      value: group.name
    }));
  };

  selectOnChangeCallback = response => {
    // eslint-disable-next-line no-console
    console.log('selectOnChangeCallback', response);
  };

  handleSubmit = (values,) => {
    const { onSuccess } = this.props;
    // same shape as initial values
    console.log(values);
    onSuccess(values);
  };

  render() {
    const { type, groups } = this.state;
    const selectData = this.mapListGroupToSelect();
    const togglePassword = type === 'password' ? 'fa fa-eye fa-lg' : 'fa fa-eye-slash fa-lg';
    const classes = `${togglePassword}`;
    return (
      <Fragment>
        <Formik
          initialValues={INITAIL_VALUES}
          validationSchema={UserValidationSchema}
          onSubmit={this.handleSubmit}
        >
          {({ errors, touched }) => (
            <Form>
              <div className="col-7">
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Username</span>
                    <span className="text-danger">*</span>
                  </label>
                  <Field name="username" type="text" className="form-control rounded-0" />
                  {errors.username && touched.username ? (
                    <div className="text-danger">{errors.username}</div>
                  ) : null}
                </div>
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Email</span>
                  </label>
                  <Field name="email" type="email" className="form-control rounded-0" />
                  {errors.email && touched.email ? (
                    <div className="text-danger">{errors.email}</div>
                  ) : null}
                </div>
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Password</span>
                    <span className="text-danger">*</span>
                  </label>
                  <div className="d-flex align-items-center">
                    <Field type={type} name="password" className="form-control rounded-0 mr-2" />
                    <span className={classes} onClick={this.togglePasswordMask} />
                  </div>
                  {errors.password && touched.password ? (
                    <div className="text-danger">{errors.password}</div>
                  ) : null}
                </div>
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Confirm Password</span>
                    <span className="text-danger">*</span>
                  </label>
                  <Field name="confirmPassword" type={type} className="form-control rounded-0" />
                  {errors.confirmPassword && touched.confirmPassword ? (
                    <div className="text-danger">{errors.confirmPassword}</div>
                  ) : null}
                </div>
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Select Group</span>
                    <span className="text-danger">*</span>
                  </label>
                  <ReactSelect
                    isMulti={false}
                    options={selectData}
                    onChangeCallback={this.selectOnChangeCallback}
                  />
                </div>
              </div>
              <button type="submit" className="btn btn-primary rounded-0 float-right mt-5 b-2">
                <span className="mx-2">Create User</span>
              </button>
            </Form>
          )}
        </Formik>
      </Fragment>
    );
  }
}

export default ViewUser;


目前,我只能访问来自 FORMIK 的值,但我想将 react select 的信息添加到这些值中,这样我每次创建时都可以显示一条带有适当信息的漂亮消息用户。

我尝试类似的方法:

<Field 
  component={({field, form}) =>
    <ReactSelect
      isMulti={false}
      options={selectData}
      value={selectData ? selectData.find(option => option.value === field.value) : ''}
      onChange={(option) => form.setFieldValue(field.name, option.value)}
      onBlur={field.onBlur}
    />} 
/>

还没有测试过(如果可行的话,应该有更简洁的方法)

一旦我有足够的时间进行测试,我会更新答案