简体   繁体   中英

React TypeError: Cannot read properties of undefined (reading 'name')

I am using React with Material UI's Textfield components. Was trying to find out the best way to set the form states with the least redundancy. Like for example, I have 8 different input fields. Instead of having a seperate handler for each input, like for example handleFirstName, handleLastName, handleEmail, handleInfo, etc.

So to accomplish this, I tried to create a handleChange handler which looks like below:

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

And on each component,

               <TextField
                className={classes.formInput}
                name="firstName"
                onChange={e => this.handleChange(e.target.value)}
                required
                id=""
                type="text"
                InputLabelProps={{
                  shrink: true,
                }}
                error={!firstName}
                helperText="Name is required"
                label="First Name"
                variant="standard" />
              <TextField
                className={classes.formInput}
                name="lastName"
                onChange={e => this.handleChange(e.target.value)}
                required
                id=""
                type="text"
                InputLabelProps={{
                  shrink: true,
                }}
                label="Last Name"
                variant="standard" />

And here is my state object

 constructor(props) {
    super(props);
    this.state = {
      firstName: '',
      lastName: '',
      ...,
    
    };
  }

These are just two of the input fields, but there are about 6 more fields that look the same. Any idea to combat this undefined name?

The problem is that you are not passing the complete event object. You are passing only the value. That is the reason why you are getting the name as undefined.

Try changing the onChange event to below -

onChange={this.handleChange}

This way you will get the complete event object in the function's e variable.

I think you need to handle multiple input field changes in single function.It is doable. try this

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

finally when to pass the onChange method to fields use :

onChange = {this.handleChange}

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