如何在React中添加带有Formik的输入

时间:2020-06-01 15:00:05

标签: javascript reactjs formik

所以这可能很简单,但我遇到了障碍。我想输入一个表单输入,但似乎无法弄清楚如何正确附加该值,以便捕获其附加字符串。

我正在使用Formik和yup进行反应。

<InputGroup>
    <Field
      id="appended-input"
      name="domain_url"
      type="text"
      value={values.domain_url}
      className={
        "form-control" +
        (errors.domain_url && touched.domain_url
          ? " is-invalid"
          : "")
      }
    />
    <ErrorMessage
      name="domain_url"
      component="div"
      className="invalid-feedback"
    />
    <InputGroupAddon addonType="append">
      .localhost
    </InputGroupAddon>
</InputGroup>

任何帮助将不胜感激。我只想让.localhost自动添加到输入项中。对于这个领域。我以为我可以做类似value =({values.domain_url} +“ .localhost”)的事情,但这似乎不起作用,而且您可能已经告诉我,我对javascript很陌生。

谢谢!

下面的完整代码,在formik状态下显示日期选择器时也遇到了问题,然后甚至有办法获取值以推送到我的getTenant(function)以传递给我的api。

static propTypes = {
    addTenant: PropTypes.func.isRequired,
  };

  onSubmit = (values) => {
    values.preventDefault();

    this.props.addTenant(values);
  };

  render() {
    const {
      domain_url,
      schema_name,
      name,
      config,
    } = this.state;

    const TenantSchema = Yup.object().shape({
      domain_url: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client URL header is required"),
      schema_name: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client db name is required"),
      name: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client name is required"),
    });
    return (
      <div className={s.root}>
        <Formik
          initialValues={{
            domain_url: "",
            schema_name: "",
            client_name: "",
            config: [
              {
                date: "",
                Tenant_description: "",
              },
            ],
          }}
          // validationSchema={TenantSchema} this is commented off because it breaks         
         submittions
          onSubmit={(values, { setSubmitting, resetForm }) => {
            setSubmitting(true);

            setTimeout(() => {
              alert(JSON.stringify(values, null, 2));
              resetForm();
              setSubmitting(false);
            }, 100);
          }}
        //onSubmit={onSubmit}

        >
          {({
            values,
            errors,
            status,
            touched,
            handleBlur,
            handleChange,
            isSubmitting,
            setFieldValue,
            handleSubmit,
            props,
          }) => (
            <FormGroup>
              <Form onSubmit={handleSubmit}>
                <legend>
                  <strong>Create</strong> Tenant
                </legend>
                <FormGroup row>
                  <Label for="normal-field" md={4} className="text-md-right">
                    Show URL
                  </Label>
                  <Col md={7}>
                    <InputGroup>
                      <Field
                        id="appended-input"
                        name="domain_url"
                        type="text"
                        value={values.domain_url}
                        onSubmit={(values) => {
                          values.domain_url = values.domain_url + ".localhost";
                        }} //this isn't working
                        className={
                          "form-control" +
                          (errors.domain_url && touched.domain_url
                            ? " is-invalid"
                            : "")
                        }
                      />
                      <ErrorMessage
                        name="domain_url"
                        component="div"
                        className="invalid-feedback"
                      />
                      <InputGroupAddon addonType="append">
                        .localhost
                      </InputGroupAddon>
                    </InputGroup>
                  </Col>
                </FormGroup>
                <FormGroup row>
                  <Label for="normal-field" md={4} className="text-md-right">
                    Database Name
                  </Label>
                  <Col md={7}>
                    <Field
                      name="schema_name"
                      type="text"
                      className={
                        "form-control" +
                        (errors.schema_name && touched.schema_name
                          ? " is-invalid"
                          : "")
                      }
                    />
                    <ErrorMessage
                      name="schema_name"
                      component="div"
                      className="invalid-feedback"
                    />
                  </Col>
                </FormGroup>
                <FormGroup row>
                  <Label for="normal-field" md={4} className="text-md-right">
                    Name
                  </Label>
                  <Col md={7}>
                    <Field
                      name="name"
                      type="text"
                      className={
                        "form-control" +
                        (errors.name && touched.name
                          ? " is-invalid"
                          : "")
                      }
                    />
                    <ErrorMessage
                      name="name"
                      component="div"
                      className="invalid-feedback"
                    />
                  </Col>
                </FormGroup>
                <FieldArray
                  name="config"
                  render={(arrayHelpers) => (
                    <div>
                      {values.config.map((config, index) => (
                        <div key={index}>
                           <FormGroup row>
                            <Label
                              md={4}
                              className="text-md-right"
                              for="mask-date"
                            >
                              Tenant Description
                            </Label>
                            <Col md={7}>
                              <TextareaAutosize
                                rows={3}
                                name={`config.${index}.tenant_description`}
                                id="elastic-textarea"
                                type="text"
                                onReset={values.event_description}
                                placeholder="Quick description of tenant"
                                onChange={handleChange}
                                value={values.tenant_description}
                                onBlur={handleBlur}
                                className={
                                  `form-control ${s.autogrow} transition-height` +
                                  (errors.tenant_description &&
                                  touched.tenant_description
                                    ? " is-invalid"
                                    : "")
                                }
                              />
                              <ErrorMessage
                                name="tenant_description"
                                component="div"
                                className="invalid-feedback"
                              />
                            </Col>
                          </FormGroup>
                          <FormGroup row>
                            <Label
                              for="normal-field"
                              md={4}
                              className="text-md-right"
                            >
                              Date
                            </Label>
                            <Col md={7}>
                              <DatePicker
                                tag={Field}
                                name={`config.${index}.date`}
                                type="date"
                                selected={values.date}
                                value={values.date}
                                className={
                                  "form-control" +
                                  (errors.date&& touched.date
                                    ? " is-invalid"
                                    : "")
                                }
                                onChange={(e) =>
                                  setFieldValue("date", e)
                                }
                              />
                              <ErrorMessage
                                name="date"
                                component="div"
                                className="invalid-feedback"
                              />
                            </Col>
                          </FormGroup>

                        </div>
                      ))}
                    </div>
                  )}
                />
                <div className="form-group">
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="btn btn-primary mr-2"
                  >
                    Save Tenant
                  </button>
                  <button type="reset" className="btn btn-secondary">
                    Reset
                  </button>
                </div>
              </Form>

              <Col md={7}>{JSON.stringify(values)}</Col>
            </FormGroup>
          )}
        </Formik>
      </div>
    );
  }
}

export default connect(null, { addTenant })(TenantForm);

1 个答案:

答案 0 :(得分:1)

如果要自定义值,可以使用 setFieldValue

https://jaredpalmer.com/formik/docs/api/formik#setfieldvalue-field-string-value-any-shouldvalidate-boolean--void

您可以添加onChange

<Field
  id="appended-input"
  name="domain_url"
  type="text"
  value={values.domain_url}
  onChange={st => {
          let value = st.target.value;
          let suffix = ".localhost";
          let index = value.indexOf(".localhost");
          if (index > 0) {
            suffix = "";
          }
     //add suffix 'localhost' if it is  not already added
          props.setFieldValue("domain_url", value + suffix);
        }}

  className={
    "form-control" +
    (errors.domain_url && touched.domain_url ? " is-invalid" : "")
  }
/>;

但是在onSubmit上添加后缀更为可取:

 onSubmit = {(values, actions) => {
       console.log('valuesbefore',values)
       values.domain_url= values.domain_url+ ".localhost"
       console.log('valuesafter',values)
       this.props.addTenant(values);
 };