繁体   English   中英

如何 append 输入与 formik 反应

[英]How to append inputs with formik in react

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

我在反应中使用 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 state中显示日期选择器时也遇到问题,然后还有如何将值推送到我的getTenant(函数)以传递给我的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);

如果要自定义值,可以使用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);
 };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM