在组件渲染后,react如何设置聚焦在特定文本字段上?

文档似乎建议使用参考,例如:

在渲染函数的输入字段上设置ref="nameInput",然后调用:

this.refs.nameInput.getInputDOMNode().focus(); 

但是我该把它叫什么呢?我在几个地方试过了,但都不行。


当前回答

使用React Hooks / Functional组件和Typescript,你可以使用useRef钩子和HTMLInputElement作为useRef的泛型参数:

import React, { useEffect, useRef } from 'react';

export default function MyComponent(): JSX.Element {
    const inputReference = useRef<HTMLInputElement>(null);

    useEffect(() => {
        inputReference.current?.focus();
    }, []);

    return (
        <div>
            <input ref={inputReference} />
        </div>
    );
}

或者如果使用reactstrap,将inputReference提供给innerRef而不是ref:

import React, { useEffect, useRef } from 'react';
import { Input } from 'reactstrap';

export default function MyComponent(): JSX.Element {
    const inputReference = useRef<HTMLInputElement>(null);

    useEffect(() => {
        inputReference.current?.focus();
    }, []);

    return (
        <div>
            <Input innerRef={inputReference} />
        </div>
    );
}

其他回答

@Dhiraj的答案是正确的,为了方便,你可以使用自动对焦道具在安装时自动对焦:

<input autoFocus name=...

注意,在jsx中,它是自动聚焦(大写F),不像普通的旧html是不区分大小写的。

您可以将该方法调用放在呈现函数中。或者在生命周期方法中,componentDidUpdate

<input type="text" autoFocus />

总是先尝试简单和基本的解决方案,对我来说很有效。

React 16.3增加了一个新的方便的方法来处理这个问题,在组件的构造函数中创建一个ref,并像下面这样使用它:

class MyForm extends Component {
  constructor(props) {
      super(props);

      this.textInput = React.createRef();
  }

  componentDidMount() {
    this.textInput.current.focus();
  }

  render() {
    return(
      <div>
        <input ref={this.textInput} />
      </div>
    );
  }
}

有关React的更多细节。createRef,你可以在React博客中查看这篇文章。

更新:

从React 16.8开始,可以在函数组件中使用useRef钩子来实现相同的结果:

import React, { useEffect, useRef } from 'react';

const MyForm = () => {
  const textInput = useRef(null);

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

  return (
    <div>
      <input ref={textInput} />
    </div>
  );
};

要将焦点移动到新创建的元素上,您可以将元素的ID存储在状态中,并使用它来设置自动聚焦。如。

export default class DefaultRolesPage extends React.Component {

    addRole = ev => {
        ev.preventDefault();
        const roleKey = this.roleKey++;
        this::updateState({
            focus: {$set: roleKey},
            formData: {
                roles: {
                    $push: [{
                        id: null,
                        name: '',
                        permissions: new Set(),
                        key: roleKey,
                    }]
                }
            }
        })
    }

    render() {
        const {formData} = this.state;

        return (
            <GridForm onSubmit={this.submit}>
                {formData.roles.map((role, idx) => (
                    <GridSection key={role.key}>
                        <GridRow>
                            <GridCol>
                                <label>Role</label>
                                <TextBox value={role.name} onChange={this.roleName(idx)} autoFocus={role.key === this.state.focus}/>
                            </GridCol>
                        </GridRow>
                    </GridSection>
                ))}
            </GridForm>
        )
    }
}

通过这种方式,没有任何文本框获得页面加载的焦点(就像我想要的那样),但是当你按下“添加”按钮来创建一个新记录时,那么这个新记录就会获得焦点。

由于autoFocus不会再次“运行”,除非组件重新挂载,所以我不必费心取消this.state.focus(即当我更新其他状态时,它不会一直窃取焦点)。