typescript - 以编程方式打开 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>)
}
解决方案
推荐阅读
- docker - Docker Volume:持久化数据以便跨远程主机访问
- python-3.x - pyplot - 带有大量箭头注释的绘图非常慢
- laravel - 在我的刀片视图中使用 @if(Auth::user()) 是否与 @auth 相同?
- prestashop - 通过模块 Prestashop 1.7 在后台创建表单
- amazon-web-services - 无服务器 - 本地路径和 Lambda 路径
- c - “if”函数,读取存储数据的问题。C 编程
- angular - 错误:容器未在 Angular 的 gvjs_dp GeoChart 中定义
- angular - 从 Angular 中的 Modal 路由到其他页面
- amazon-ec2 - 来自 lamda 函数的 EC2 实例调用
- bash - awk 和转义字符