【问题标题】:How do I set autofocus to an input that's inside a select dropdown?如何将自动对焦设置为选择下拉列表中的输入?
【发布时间】:2021-11-26 02:20:26
【问题描述】:

我在选择下拉列表中有一个输入字段。当用户单击下拉菜单时,我需要立即关注该输入框。我尝试使用 refs,但这似乎不起作用。我正在使用 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"
        />
...

Input ref 的 useEffect:

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

我尝试了上述 useEffect 的变体,我没有在 inputRef 上监听更改,而是在加载下拉列表时监听了更改。但是他们都没有工作。

这里的任何帮助将不胜感激......

【问题讨论】:

标签: javascript reactjs antd


【解决方案1】:

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

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

Here 是一个反应类组件的工作堆栈。

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

更多选项请参见how-to-set-focus-on-an-input-field-after-rendering

链接完整示例的代码:

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'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 2021-11-12
    • 1970-01-01
    • 2011-04-24
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多