簡體   English   中英

在抽屜中調用setState()onChange時選擇文本字段的錯誤

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

我有一個Material-UI抽屜,在其中,我有一個TextField選擇輸入。 我可以打開下拉菜單,但是當我單擊任何選項時,它將刪除整個頁面的內容並在控制台上產生許多錯誤。

我正在學習React,所以可能是基本的東西。

我進行了一些測試,發現它只有在以下情況下才會中斷:

  1. 我在onChange屬性調用的函數中調用setState()
  2. TextField選擇位於Drawer組件內部。

我的代碼:

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

控制台上的錯誤:

控制台錯誤

我唯一看到的是您尚未將事件傳遞給this.handleCityChange方法。

嘗試將事件傳遞給這樣的方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM