Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

javascript - How to set a general onchange for the dynamic form fields coming from api in react js.?

I am working with forms in react.

The challenge I am facing is whenever i set an onchange handler for the input field, it changes the value for all the input fields I have.

Form input fields are mapped and are coming from the api. What I want is a generic on change handler to manage all the input fields.

import React, { Component } from "react";
import {
  TextInputComponent,
  RadioInputComponent,
  SelectComponent,
} from "../../components/index";
import IntlMessages from "../../common/constants/IntlMessages";

class DummyForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      field: "",
      checkBox: "",
      options: "",
      radioField: "",
      error: "",
    };
  }
  componentDidMount() {
    const code = window.location.pathname.split("/")[2];
    this.props.getEmsForms(code);
  }

//this my on change handler and it would be great help if someone can tell where iam wrong.
  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value,
    }) 
  }

  submit = () => {
    const { field, checkBox, options, radioField } = this.state;
    const auth = this.props.user.data.user.access_token;
    this.props.updateEmailPhone({
      email,
      address,
      auth,
    });
  };

  render() {
    return (
      <React.Fragment>
        <div className="row justify-content-center py-2 my-2">
          <div className="col-sm-12 col-lg-5 col-md- border border-info bg-light">
            <div className="row p-3">
              {this.props.getForms.data
                ? this.props.getForms.data.map((item) => {
                    return (
                      <div className="col-12 p-2">
                        {item.inputType == "textbox" ? (
                          <TextInputComponent
                            key={item.fieldName}
                            label={item.fieldLabelText}
                            type="text"
                            placeholder={item.fieldName}
                            value={this.state.field}
                            onChange={(e) =>
                              this.handleChange(e, "field")
                            }
                          />
                        ) : item.inputType == "dropdown" ? (
                          <>
                            <label>{item.fieldLabelText}</label>
                            <select
                              className="custom-select "
                              id="inputGroupSelect01"
                              onChange={(e) =>
                                this.handleChange({ options: e.target.value })
                              }
                            >
                              {item.inputOptions.map((key) => (
                                <option>{key.value}</option>
                              ))}
                            </select>
                          </>
                        ) : item.inputType == "checkbox" ? (
                          <SelectComponent
                            name={"select2"}
                            value={this.state.checkBox}
                            label={item.fieldLabelText}
                            onChange={(e) =>
                              this.setState({ checkBox: e.target.value })
                            }
                          />
                        ) : item.inputType == "radio" ? (
                          <RadioInputComponent
                            title="gender"
                            value={this.state.gender}
                            name={item.fieldLabelText}
                            onChange={(e) => {
                              this.setState({ radioField: e.target.value });
                            }}
                          />
                        ) : null}
                      </div>
                    );
                  })
                : this.props.getForms.messages}

              <div className="row" style={{ marginTop: "50px" }}>
                {/* <div className="col d-flex justify-content-start">
              <button className="btn-danger" onClick={this.toggleModal}>
              Ja
              </button>
            </div> */}
                {this.props.getForms.data && (
                  <div className="col d-flex justify-content-end">
                    <button className="btn btn-success button-margin">
                      <IntlMessages id="blank.button" />
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </React.Fragment>
    );
  }
}

export default DummyForm;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get the name, value, type and checked attributes from the event target and set state with those in a shape like

{
  "input": "a",
  "select": "2",
  "radio": "3",
  "checkbox1": true,
  "checkbox3": true,
  "checkbox2": true
}
import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [state, setState] = useState({});

  const onChange = (e) => {
    const { name, value, checked, type } = e.target;
    const newVal = type === "checkbox" ? checked : value;

    setState({
      ...state,
      [name]: newVal
    });
  };

  return (
    <>
      <div className="section">
        <label>
          Input
          <input name="input" onChange={onChange} />
        </label>
      </div>
      <div className="section">
        <label>
          select
          <select name="select" onChange={onChange}>
            <option>1</option>
            <option>2</option>
            <option>3</option>
          </select>
        </label>
      </div>
      <div className="section">
        <fieldset>
          <legend>Radio</legend>
          <label>
            <input type="radio" name="radio" value="1" onChange={onChange} />1
          </label>

          <label>
            <input type="radio" name="radio" value="2" onChange={onChange} />2
          </label>

          <label>
            <input type="radio" name="radio" value="3" onChange={onChange} />3
          </label>
        </fieldset>

        <fieldset>
          <legend>Checkbox</legend>
          <label>
            <input type="checkbox" name="checkbox1" onChange={onChange} />1
          </label>

          <label>
            <input type="checkbox" name="checkbox2" onChange={onChange} />2
          </label>

          <label>
            <input type="checkbox" name="checkbox3" onChange={onChange} />3
          </label>
        </fieldset>

        <pre>{JSON.stringify(state, null, 2)}</pre>
      </div>
    </>
  );
}

Edit interesting-leftpad-km0f7


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...