如何将自动对焦设置为选择下拉列表中的输入?



在选择下拉菜单中有一个输入字段。我需要专注于输入框,只要下拉框显示当用户单击它。我试着用裁判,但那似乎不起作用。我使用的是antd 3.26.14和React 16.8.6。下面是代码:

<Select
labelInValue
open={isOpenSelectCategory}
onDropdownVisibleChange={onDropdownVisibleChange}
placeholder="Select Category"
onChange={() => {
searchDropdownOptions('formCategories', '');
setCategoryInputValue('');
}}
notFoundContent={null}
dropdownRender={menu => (
<>
<div
onMouseDown={lockSelectCategoryClose}
onMouseUp={lockSelectCategoryClose}
style={{ marginBottom: '10px' }}
>
<Input
value={categoryInputValue}
ref={inputRef}
onChange={event => {
searchDropdownOptions(
'formCategories',
event.target.value,
);
setCategoryInputValue(event.target.value);
}}
placeholder="Search category or create new one"
/>
...

输入的useEffect ref:

useEffect(() => {
if (inputRef.current) inputRef.current.focus();
}, [inputRef]);

我已经尝试了上述useEffect的变化,而不是听inputRef的变化,我听了下拉菜单加载时的变化。

任何帮助都将是非常感激的…

尝试将ref={(input) => input && input.focus()}autofocus属性结合使用,例如:

<Input
autofocus
ref={(input) => input && input.focus()}
...
/>

这是一个react类组件的工作stackblitz。

注意:这个解决方案的问题是它将输入集中在任何重新渲染上(这可能不是想要的)。

更多选项请参见如何在渲染后设置focus-on-an-input-field。

链接完整示例的代码:
import React, { useFocus } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Select, Divider, Input } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
const { Option } = Select;
let index = 0;
class App extends React.Component {
state = {
items: ['jack', 'lucy'],
name: '',
};
onNameChange = (event) => {
this.setState({
name: event.target.value,
});
};
addItem = () => {
console.log('addItem');
const { items, name } = this.state;
this.setState({
items: [...items, name || `New item ${index++}`],
name: '',
});
};
render() {
// const [inputRef, setInputFocus] = useFocus();
const { items, name } = this.state;
return (
<Select
style={{ width: 240 }}
placeholder="custom dropdown render"
dropdownRender={(menu) => (
<div>
{menu}
<Divider style={{ margin: '4px 0' }} />
<div style={{ display: 'flex', flexWrap: 'nowrap', padding: 8 }}>
<Input
autofocus
ref={(input) => input && input.focus()}
style={{ flex: 'auto' }}
value={name}
onChange={this.onNameChange}
/>
<a
style={{
flex: 'none',
padding: '8px',
display: 'block',
cursor: 'pointer',
}}
onClick={this.addItem}
>
<PlusOutlined /> Add item
</a>
</div>
</div>
)}
>
{items.map((item) => (
<Option key={item}>{item}</Option>
))}
</Select>
);
}
}
ReactDOM.render(<App />, document.getElementById('container'));

最新更新