如何在 onChange 后清除 Material-ui 中的自动完成输入?

Guy*_*Guy 9 reactjs material-ui react-hooks

材质 UI的钩子版本中,我似乎无法在 onChange 事件后清除自动完成功能:

// @flow
import React, { useRef, useState } from "react";
import "./Autocomplete.scss";
import AutocompleteUI from "@material-ui/lab/Autocomplete";
import TextField from "@material-ui/core/TextField";

function Autocomplete(props) {
    const { options } = props;
    const [value, setValue] = useState();

    const container = useRef();
    const input = useRef();

    function onChange(event, newValue) {
        if (!newValue) return;
        props.onChange(newValue);
        setValue(undefined);
        input.current.value = "";
        event.target.value = "";
    }

    function renderInput(params) {
        return (
            <TextField
                inputRef={input}
                {...params}
                inputProps={{
                    ...params.inputProps,
                    autoComplete: "disabled", // disable autocomplete and autofill
                }}
                margin="none"
                fullWidth
            />
        );
    }

    return (
        <div className="Autocomplete-container">
            {value}
            <AutocompleteUI
                ref={container}
                options={options}
                autoHightlight={true}
                clearOnEscape={true}
                autoSelect={true}
                // freeSolo={true}
                getOptionLabel={option => option.title}
                renderInput={renderInput}
                value={value}
                onChange={onChange}
            />
        </div>
    );
}

export default Autocomplete;
Run Code Online (Sandbox Code Playgroud)

深入研究源代码我注意到该组件在内部使用useAutocomplete钩子。但是,位于该钩子内部的setInputValueresetInputValue都没有暴露在外面。有没有办法在 onChange 之后完成输入清除?

小智 9

您需要将 inputValue 属性设置为 valueState ,并且在 onhange 函数上只需清除 valueState

<Autocomplete

inputValue={valueState}

onChange={(value, option) =>
{


    setOptions([])
    setValueState("")

}}

renderInput={params => (
    <TextField
        dir="rtl"
        onChange={(event) =>
        {

            setValueState(event.target.value)

        }}
        {...params}
        label="Search Patient"
        variant="filled"

        InputProps={{
            ...params.InputProps,
            endAdornment: (
                <React.Fragment>
                    {loading ? (
                        <CircularProgress color="inherit" size={20} />
                    ) : null}
                    {params.InputProps.endAdornment}
                </React.Fragment>
            )
        }}
    />
)}
/>
Run Code Online (Sandbox Code Playgroud)


小智 -2

哟!我非常确定材料中的 Textfield 组件采用“autoComplete”属性,并且您可以传递字符串“false”。另外,它不会进入 inputProps,尝试一下。

<Textfield autoComplete="false" />
Run Code Online (Sandbox Code Playgroud)