簡體   English   中英

如何使用自定義鈎子在 MUI v5 中處理 AutoComplete {onChange}

[英]How to handle AutoComplete {onChange} in MUI v5 using a custom hook

我正在使用一個自定義掛鈎來驗證和處理 onChange function。

對於大多數組件(輸入,Select,TextField),我處理 onChange 沒有問題; 我正在使用以下語法來處理 onChange,除了 AutoComplete 之外,它工作正常。

無自動完成組件:

onChange = {handleInputChange}

const handleInputChange = (e) => {
    const { name, value } = e.target;
    setValues({
      ...values,
      [name]: value,
    });
    if (validateOnChange) validate({ [name]: value });
  };

讓我們看看 e.target 在此處輸入圖像描述

但是當它與 AutoComplete 相比時,它看起來與上面的屏幕截圖完全不同。 我無法通過 setValues 獲取名稱或值以正確跟蹤它。

在此處輸入圖像描述

我使用了 function 道具:

const {onChange} = props;   

<Autocomplete
    onChange={(e, value) => onChange(value)}

如果你想完整地看到它:

import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
import CircularProgress from '@mui/material/CircularProgress';
import {useRef} from "react";

export default function Asynchronous(props) {
    const {onChange, name, getListData, label = "name", id = "id", showName,defaultValue,disabled,required,value,noOption="No Option"} = props;
    const [open, setOpen] = React.useState(false);
    const [options, setOptions] = React.useState([]);
    const [filters, setFilters] = React.useState(null);
    const [loadingApi, setLoadingApi] = React.useState(false)
    const loading = open && options.length === 0;
    let timeOut = useRef(null);

    const getData = async (search = "") => {
        setLoadingApi(true)
        const data = await getListData(search); // For demo purposes.
        // console.log(data)
        setLoadingApi(false);
        // console.log(data)
        if(data)
        setOptions([...data]);
    }

    React.useEffect(() => {

        if (!loading) {
            return undefined;
        }
        getData();

    }, [loading]);

    React.useEffect(() => {
        if (filters !== null) {
            if (timeOut.current !== null)
                clearTimeout(timeOut.current);

            timeOut.current = setTimeout(() => getData(filters), 500);
        }
    }, [filters]);

    React.useEffect(() => {
        if (!open) {
            setOptions([]);
        }
    }, [open]);

    return (
        <Autocomplete
            disabled={disabled}
            id={name}
            name={name}
            sx={{width: "100%"}}
            open={open}
            onOpen={() => {
                setOpen(true);
            }}
            onClose={() => {
                setOpen(false);
            }}
            defaultValue={defaultValue}
            value={value}
            isOptionEqualToValue={(option, value) => option?.[id] === value?.[id]}
            getOptionLabel={(option) => option?.[label]}
            options={options}
            onChange={(e, value) => onChange(value)}
            loading={loadingApi}
            noOptionsText={noOption}
            renderInput={(params) => (
                <TextField variant="standard"
                    name={name}
                    required={required}
                    variant="standard"
                    {...params}
                    label={showName}
                    onChange={(e) => setFilters(e.target.value)}
                    InputProps={{
                        ...params.InputProps,
                        onblur:() => {},
                        endAdornment: (
                            <React.Fragment>
                                {loadingApi ? <CircularProgress color="inherit" size={20}/> : null}
                                {params.InputProps.endAdornment}
                            </React.Fragment>
                        ),
                    }}
                />
            )}
        />
    );
}

暫無
暫無

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

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