首页 > 解决方案 > 以编程方式打开 Material-UI Select 时失去焦点

问题描述

我正在尝试根据 TextField 输入开发一个作为过滤选择的钩子。当用户在 TextField 中键入时,我喜欢显示可供选择的可用项目列表。我曾尝试使用 Select 的打开状态属性,但是当我触发它时,TextField 会失去焦点,转而支持 Select,这在您键入时确实不切实际。

我正在寻找一种在不失去焦点的情况下显示列表的方法,知道吗?

import * as React from 'react';
import {
    FormControl, InputLabel, MenuItem, TextField, Select
} from '@material-ui/core';

export default function AddressSearchLookup(props: any) {
    const [key, setKey] = React.useState('');
    const [openSelect, setOpenSelect] = React.useState(false);

    const [filteredAddresses, setFilteredAddresses] = React.useState([] as any);

    React.useEffect(() => {
        if (key.length > 0) {
            var addrs = props.Addresses;
            addrs = addrs.filter((a: any) => a.key.toLowerCase().startsWith(key.toLowerCase()));

            setFilteredAddresses(addrs);
        }
        else
            props.OnAddressChange('');
    }, [key]);

    const onSelectAddress = (e:any) => {
        if(key !== e.target.value)
            setKey(e.target.value);

        props.OnAddressChange(e.target.value);
    }

    const onKeyFieldChanged = (e: any) => {
        if (key !== e.target.value)
            setKey(e.target.value);

        setOpenSelect(true);
    }

    return (<span style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
        <FormControl variant="outlined" style={{ width: '30%' }}>
            <TextField
                value={key}
                variant="outlined"
                label={"Key"}
                name="key-label-placeholder"
                onChange={onKeyFieldChanged}
                inputProps={{
                    name: 'keySearchAddress',
                    id: 'keySearchAddress'
                }}
            />
        </FormControl>
        <FormControl variant="outlined" style={{ width: '70%' }}>
            <InputLabel id="address-select-outlined-label" >Adresse</InputLabel>
            <Select
                labelId="address-select-outlined-label"
                id="address-select-select-outlined"
                name="address"
                open={openSelect}
                onClose={() => setOpenSelect(false)}
                onOpen={() => setOpenSelect(true)}
                value={props.Address}
                onChange={onSelectAddress}
                label="Addresse"
                displayEmpty
            >
                {
                    filteredAddresses.map((ctr: any) => {
                        if ('text' in ctr)
                            return (<MenuItem key={ctr.key} value={ctr.key}>{ctr.text}</MenuItem>);
                        else
                            return null;
                    })
                }
            </Select>
        </FormControl>
    </span>)
}

标签: typescriptreact-hooksmaterial-ui

解决方案


推荐阅读