无法使用 material-ui 中的 select 项使用 onchange 自动完成获取 event.target.value

Cant get event.target.value using select item from material-ui autocomplete with onchange

*** 根据建议更新了代码 ****** 我正在学习使用 material-ui。我找不到很多将它与事件处理相结合的例子。我使用了自动完成和文本字段来创建从 API 中获取的数据的建议列表。我可以呈现选定的列表,但是在单击其中一个选项时,我无法将单击的值传递给反应 class 的成员函数。我需要将事件正确绑定到自动完成吗?我应该怎么做。我的代码中的第 25 行将事件目标记录到控制台,但它始终为 0(我假设为 null)。如何将 this.state.data 的值设置为单击的选项?

我尝试添加 autoSelect={true}

我也试过将这行代码移到文本区域中。
onChange={this.updateState}

import React from "react"
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';

class App extends React.Component {


    constructor(props) {
        super(props);

        this.state = {
            data: null,
            isLoaded: false,
            itemSelected: false,
            inputVal: ''}

            this.updateState = this.updateState.bind(this)

        };

        updateState(e) {
            e.persist()
            const newValue = e.target.value
            this.setState({inputVal: newValue, itemSelected: true});
            console.log(e.target.value);

            // eventually I want to render a DIV with data from the selected value
        }

        /// fetch some data

    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            /* .then(json => console.log(json)) */

            .then(data => this.setState({data, isLoaded: true}));
    }

    render() {

        const {isLoaded, itemSelected} = this.state;




        if (!isLoaded) {
            return <div> loading ...</div>;
        } else if (itemSelected) {
            return <div> item selected </div>
        } else {
            const limo = this.state.data;
            return (
                <div>

                    <Autocomplete
                        freeSolo
                        disableClearable
                        autoSelect={true}
                        id = "limoSelect"
                        onChange={this.updateState}
                        value = {this.state.inputVal}
                        options={limo.map(option => "body: '" + option.body + '\n' + "'      id: " + option.id)}
                        renderInput={params => (

                            <TextField
                                {...params}
                                label="Type In Content"
                                id="limoText"
                                value = ''
                                autoSelect={true}
                                margin="normal"
                                variant="outlined"
                                fullWidth
                                InputProps={{...params.InputProps, type: 'search'}}

                            />


                        )}
                    />
                </div>
            );

        }
    }
}

App.defaultProps = {}

export default App;

控制台记录为零。 当您单击该选项时,将调用 updateState 并设置此变量 this.state.itemSelected = 真; 没有错误信息。 我希望 updateState 中的 console.log 可以记录点击的项目!

编辑:使用e.target.textContent 即可。
这是一个实时 Codesandbox 检查代码(修改了一些部分,应用下面的提示和其他一些东西)。


不要像这样手动改变状态:

this.state.itemSelected = true

使用 setState(就像您已经对其他状态项所做的那样):

 updateState(e) {
    this.setState({ inputVal: e.target.value, itemSelected: true });
    console.log(e.target.value);
    // eventually I want to render a DIV with data from the selected value
  }

还有个小技巧,可以使用数组解构:

const {isLoaded, itemSelected} = this.state;

而不是

var isloaded = this.state.isLoaded;
var itemSelected = this.state.itemSelected;

onChange 签名:函数(事件:对象,值:任意)=> void

这是一个例子:

import React from 'react';
import Chip from '@material-ui/core/Chip';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField from '@material-ui/core/TextField';

export default class Tags extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tags: []
    };
    this.onTagsChange = this.onTagsChange.bind(this);
  }

  onTagsChange = (event, values) => {
    this.setState({
      tags: values
    }, () => {
      // This will output an array of objects
      // given by Autocompelte options property.
      console.log(this.state.tags);
    });
  }

  render() {
    return (
      <div style={{ width: 500 }}>
        <Autocomplete
          multiple
          options={top100Films}
          getOptionLabel={option => option.title}
          defaultValue={[top100Films[13]]}
          onChange={this.onTagsChange}
          renderInput={params => (
            <TextField
              {...params}
              variant="standard"
              label="Multiple values"
              placeholder="Favorites"
              margin="normal"
              fullWidth
            />
          )}
        />
      </div>
    );
  }
}

const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1974 },
  { title: 'The Dark Knight', year: 2008 },
  { title: '12 Angry Men', year: 1957 },
  { title: "Schindler's List", year: 1993 },
  { title: 'Pulp Fiction', year: 1994 },
  { title: 'The Lord of the Rings: The Return of the King', year: 2003 },
  { title: 'The Good, the Bad and the Ugly', year: 1966 },
  { title: 'Fight Club', year: 1999 },
  { title: 'The Lord of the Rings: The Fellowship of the Ring', year: 2001 },
  { title: 'Star Wars: Episode V - The Empire Strikes Back', year: 1980 },
  { title: 'Forrest Gump', year: 1994 },
  { title: 'Inception', year: 2010 },
];