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

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

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

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

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


当前回答

本卡普的解决方案在打字稿

React 16.8 +功能组件- useFocus钩子

export const useFocus = (): [React.MutableRefObject<HTMLInputElement>, VoidFunction] => {
  const htmlElRef = React.useRef<HTMLInputElement>(null);
  const setFocus = React.useCallback(() => {
    if (htmlElRef.current) htmlElRef.current.focus();
  }, [htmlElRef]);

  return React.useMemo(() => [htmlElRef, setFocus], [htmlElRef, setFocus]);
};

其他回答

我也有同样的问题,但我也有一些动画,所以我的同事建议使用window.requestAnimationFrame

这是元素的ref属性:

ref={(input) => {input && window.requestAnimationFrame(()=>{input.focus()})}}

重点关注功能组件使用createRef

给使用功能组件的开发人员。这似乎很合适。点击按钮后,焦点发生在inputfield上。我也附上了CodeSandbox链接。

import React from 'react';

export default function App() {
  const inputRef = React.createRef();
  return <>
    <input ref={inputRef} type={'text'} />
    <button onClick={() => {if (inputRef.current) { inputRef.current.focus() }}} >
      Click Here
    </button>
  </>
}

https://codesandbox.io/s/blazing-http-hfwp9t

从React 0.15开始,最简洁的方法是:

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

自动对焦对我来说效果最好。我需要将一些文本更改为双击文本的输入,所以这是我最终得到的:

<input autoFocus onFocus={this.setCaretToEnd} value={this.state.editTodo.value} onDoubleClick={this.updateTodoItem} />

注意:要修复React在文本开头放置插入符号的问题,请使用以下方法:

setCaretToEnd(event) {
    var originalText = event.target.value;
    event.target.value = '';
    event.target.value = originalText;
}

在这里找到: https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js

在尝试了上面的许多选项后,没有成功,我发现这是因为我禁用了输入,然后启用了输入,导致焦点丢失。

我有一个道具sendingAnswer将禁用输入,而我轮询后端。

<Input
  autoFocus={question}
  placeholder={
    gettingQuestion ? 'Loading...' : 'Type your answer here...'
  }
  value={answer}
  onChange={event => dispatch(updateAnswer(event.target.value))}
  type="text"
  autocomplete="off"
  name="answer"
  // disabled={sendingAnswer} <-- Causing focus to be lost.
/>

一旦我拆除了瘫痪的道具,一切又开始工作了。