简体   繁体   中英

ReactJS Ref: undefined error getting input element value

In the following code I am setting up a ref on the <input/> element which is used during the <form> element's onSubmit handler.

For some reason I am getting the following error when submitting the form:

TypeError: Cannot read property 'value' of undefined

How can I prevent this error?

import React from "react";

class AddItemForm extends React.Component {

  nameRef = React.createRef();

  createItem = event => {

    event.preventDefault();

    const item = {
      name: this.nameRef.value.value,      
    };  
  }

  render() {
    return (
      <form className="item-edit" onSubmit={this.createItem}>
        <input name="name" ref={this.nameRef} type="text" placeholder="Name" />        
        <button type="submit">+ Add Item</button>
      </form>
    );
  }
}

export default AddItemForm;

You need to replace the first value with current seeing that the ref object provides access to the underlying DOM element via that field.

The following should resolve your problem:

createItem = event => {
    event.preventDefault();
    const item = {
       name: this.nameRef.current.value,      // Replace value with current 
    };
    console.log(item);      
}

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