简体   繁体   中英

how to get input field values in react?

I am adding dynamically input fields .I want to get it's value .can you please tell me how I will get it's value

here is my code https://codesandbox.io/s/adoring-meninsky-hu3f8

return (
    <div className="App">
      <Form>
        {state.inputs.map(input => (
          <KeyValue />
        ))}
        <Button type="button" primary onClick={appendInput}>
          Add
        </Button>
      </Form>
    </div>
  );

I want to get it's value how ?

any update

I will put a name for each input and pass it a onChange function. Then in my onChange function i will set my State depend on the name.

Function

onChange = e => {
  this.setState({[e.target.name] : e.target.value});
}

Render

render(){
return (
    <div className="App">
      <Form>
        {state.inputs.map(input => (
          <KeyValue name={input.name} value={this.state[input.name]} onChange={this.onChange } />
        ))}
        <Button type="button" primary onClick={appendInput}>
          Add
        </Button>
      </Form>
    </div>
  );

}

Here is my solution https://codesandbox.io/s/pensive-lake-erynd

pass function to KeyValue component to get values when input changes

  const handleChangeKeyValues = name => value => {
    setState(prevState => {
      const newValues = {
        ...prevState.values,
        [name]: value
      };

      return {
        ...prevState,
        values: newValues
      };
    });
  };

and receives values from props and handle inputs in KeyValue component

const KeyValue = ({ onChange, values = { firstName: "", lastName: "" } }) => {
  const handleChangeInput = event => {
    const { value, name } = event.target;

    const newFormValue = { ...values, [name]: value };

    onChange(newFormValue);
  };

  return (
    <Form.Group widths="equal">
      <Form.Input
        value={values.firstName}
        fluid
        label="Key"
        name="firstName"
        placeholder="First name"
        onChange={handleChangeInput}
      />
      <Form.Input
        value={values.lastName}
        fluid
        label="Value"
        name="lastName"
        placeholder="Last name"
        onChange={handleChangeInput}
      />
      <Icon style={{ top: 30, position: "relative", left: 10 }} name="delete" />
      <Form.Input
        style={{ display: "none" }}
        fluid
        label=""
        placeholder="Last name"
      />
    </Form.Group>
  );
};

Store values in state under unique name for each inputs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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