如何在自动完成材料ui上使用onchange?

时间:2019-12-09 23:33:00

标签: reactjs autocomplete material-ui react-hooks

使用handleChange方法处理具有钩子样式的Form Input的OnChange事件,该事件将对象设置为关闭状态。

handleChange函数依次调用setLocation,该函数将使用新值更新位置状态。

为了使用户数据输入更加容易,我决定将城市字段更改为自动完成功能,但是无法捕获自动完成功能的值。 他在文档中告诉我,我需要传递两个参数,但我不太了解

function(event: object, value: any) => void
event: The event source of the callback
value: null

当我输入数据时,这就是我选择自动完成选项时在控制台中抛出的东西

event.target.name
Undefined
event.target.value
0

但是从其他字段中我确实得到了值

event.target.name
State
event.target.value
Oregon
event.target.name
Zip_code
event.target.value
99501

如何访问该字段的值并将其放入函数中以插入数据?

 import React, { useState, useEffect} from "react"; 
    import  axios  from 'axios';
    import TextField from '@material-ui/core/TextField';
    import {  Typography,Button} from '@material-ui/core';
    import Autocomplete from '@material-ui/lab/Autocomplete'
    import { makeStyles } from '@material-ui/core/styles';

    const useStyles = makeStyles(theme => ({
        option: {
          fontSize: 15,
          '& > span': {
            marginRight: 10,
            fontSize: 18,
          },
        },
      }));

    function LocationAdd(props) {

      const classes = useStyles();

      const[list, setList]=useState({Data:[]});

    useEffect(()=>{
      const getList=async()=>{
              const response =await axios.get('/apirest/ListCity');
              setList(response.data);
      }
      getList();
    },[]);

      const initialState = { City: '', State: '', Zip_code:0 }

      const [location, setLocation] = useState(initialState) 

      function handleChange(event) { 
        setLocation({...location, [event.target.name]: event.target.value})
      }

      function handleSubmit(event) { 
        event.preventDefault();  

        if(!location.City || !location.State || !location.Zip_code) return 
        async function postLocation() {
          try {
            const response = await axios.post('/apirest/addLocation', location); 
            props.history.push(`/location/${response.data._id}`);  
          } catch(error) {
            console.log('error', error);
          }
        }
        postLocation();
      }

      function handleCancel() {
        props.history.push("/location");
      }

      return ( 
        <div style={{ padding: 16, margin: 'auto', maxWidth: 1000 }}> 
        <Typography variant="h4" align="center" component="h1" gutterBottom>
        Add
      </Typography>
        <form onSubmit={handleSubmit}>

        <Autocomplete
        style={{ width: 300 }}
        value={location.City}
        onChange={handleChange}
        options={list.City}
        classes={{
          option: classes.option,
        }}
        autoHighlight
        getOptionLabel={option => typeof option === 'string' ? option : option.City}
        renderOption={option => (
          <React.Fragment>

            {option.City} -{option.State}
          </React.Fragment>
        )}

         renderInput={params => (
           <TextField {...params} label="City"  value={location.City}  margin="normal" variant="outlined" style={{ width: 220 }} inputProps={{
             ...params.inputProps,
             autoComplete: 'disabled', // disable autocomplete and autofill
           }}/>
         )}
       />

          <TextField
            name="State"
            label="State"
            value={location.State}
            onChange={handleChange}
            margin="normal"
            variant="outlined"
          />
          <TextField
            name="Zip_code"
            label="Zip_code"
            value={location.Zip_code}
            onChange={handleChange}
            margin="normal"
            variant="outlined"
          />
            <Button
                variant="contained"
                color="primary"
                type="submit">
                      Add
            </Button>

        </form>
        </div>
      );
    }

    export default LocationAdd

4 个答案:

答案 0 :(得分:0)

如果您只是想获取用户类型输入的值,则需要使用onInputChange。当用户从下拉菜单中选择一个选项时,onChange处理程序将运行。

export default function ComboBox() {
  function handleInputChange(event, value) {
    console.log(value);
  }

  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option: FilmOptionType) => option.title}
      style={{ width: 300 }}
      onInputChange={handleInputChange}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />
  );
}

Codesandbox

答案 1 :(得分:0)

react SyntheticEvent在异步请求中设置了null目标,请尝试使用

  

event.persist()

关于事件

https://reactjs.org/docs/events.html#event-pooling

 const handleOnChangeText=(event)=> {     
    event.persist();
    console.log(event)    
    let active = true;
    setOpen(true);
    if (!loading) {
      return undefined;
    }
    (async () => {
      const response = await fetch('https://country.register.gov.uk/records.json?page-size=5000');
      await sleep(1e3); // For demo purposes.
      const countries = await response.json();
      if (active) {
        setOptions(Object.keys(countries).map(key => countries[key].item[0]) as CountryType[]);
      }
      active = false;
    })();   
}



<Autocomplete
      id="comboboxAsync"
      disableOpenOnFocus
      style={{ width: 300 }}
      open={open}
      onInputChange={handleOnChangeText}
...

答案 2 :(得分:0)

Id 在这种模式下被检索:id-option-numberOfOption,这就是为什么我必须拆分检索到的值以更新状态

const handleAutoCompleteChange = (event, value) => {
          this.setState({ ...this.state, [event.target.id.split("-")[0]]: value });
          console.log([event.target.id.split("-")[0]],value);
}

答案 3 :(得分:-1)

您可以使用mui-autocomplete npm进行简单且更少编码的更多选项(如头像视图异步调用)。您应该尝试一下。这是更多信息的示例,请访问此处。 [http://mui-autocomplete.com/home]

`import React from 'react';
 import MuiAutocomplete from 'mui-autocomplete';
 const cities = [
 {
   id: 1,
   name: "Alabama",
   code: "AL"
 },
 {
   id: 2,
   name: "Alaska",
   code: "AK"
 },
 {
   id: 3,
   name: "American Samoa",
   code: "AS"
 }];
 function Home () {
   return (
     <div>
      <MuiAutocomplete
       placeholder="Countries"
       name="countries"
       setvalue={1}
       setdata={cities}
       variant="outlined"
       template={{
        title: 'name'
       }}
      />
    </div>
    );
 }`