简体   繁体   English

在抽屉中调用setState()onChange时选择文本字段的错误

[英]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. 我有一个Material-UI抽屉,在其中,我有一个TextField选择输入。 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. 我正在学习React,所以可能是基本的东西。

I made some tests and discovered that it only breaks when: 我进行了一些测试,发现它只有在以下情况下才会中断:

  1. I call setState() in a function called by an onChange property. 我在onChange属性调用的函数中调用setState()
  2. The TextField select is inside a Drawer component. TextField选择位于Drawer组件内部。

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. 我唯一看到的是您尚未将事件传递给this.handleCityChange方法。

try passing the event into the method like this: 尝试将事件传递给这样的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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