简体   繁体   中英

Error when calling setState() onChange of a select TextField inside a Drawer

I have a Material-UI Drawer and inside of it, I have a TextField select input. I can open the dropdown fine, but when I click on any option, it removes the content of the entire page and generates many errors on the console.

I'm learning React so it's probably something basic.

I made some tests and discovered that it only breaks when:

  1. I call setState() in a function called by an onChange property.
  2. The TextField select is inside a Drawer component.

My code:

import React, { Component } from 'react';

import './styles.scss';

import Drawer from '@material-ui/core/Drawer';

import MenuItem from '@material-ui/core/MenuItem';
import TextField from '@material-ui/core/TextField';

class Filter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filter_open: true,
      form: {
        city: ''
      },
      cities: [
        {
          id: 1,
          label: 'Lorem'
        },
        {
          id: 2,
          label: 'Ipsum'
        }
      ]
    }
  }

  handleCityChange = (changeEvent) => {
    this.setState({
      form: {
        city: changeEvent.target.value
      }
    });
  }

  render() {
    return (
      <Drawer
        anchor="bottom"
        open={this.state.filter_open}
        transitionDuration={450}
      >
        <div className="Filter">
          <TextField
            id="filled-select-city"
            className="TextField"
            select
            label="Select an option"
            value={this.state.form.city}
            onChange={this.handleCityChange}
            margin="normal"
          >
            {this.state.cities.map(option => (
              <MenuItem key={option.id} value={option.id}>
                {option.label}
              </MenuItem>
            ))}
          </TextField>
        </div>
      </Drawer>
    )
  }
}

export default Filter

The errors on the console:

控制台错误

The only thing I can see is you haven't passed the event to the this.handleCityChange method.

try passing the event into the method like this:

onChange={(e) => {this.handleCityChange(e);}}

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