如何以编程方式将焦点设置到React输入框?

16 浏览
0 Comments

如何以编程方式将焦点设置到React输入框?

我正在尝试实现一个非常简单的用例,即 UI 特性,其中:

  1. 有一个包含内容的标签
  2. 如果点击标签,将用标签的内容替换为文本输入框
  3. 用户可以编辑内容
  4. 按下回车键后,输入框隐藏,标签重新显示,并更新内容

最终我能够成功实现所有功能(事实上,使用了 MongoBD 后端、Redux 等),唯一做不到的是(Google 和阅读 S.O.F 相似帖子花了整整一天):

当我的文本输入框出现时,我无法将焦点转移到它上面!首先我尝试了这个方法:

{this.state.word}

 

但是 autoFocus 明显不起作用(我“猜测”是因为表单被渲染,但处于隐藏状态,使得 autoFocus 无用)。

接下来在我的 this.updateWor 中尝试了很多在 Google 和 S.O.F 上找到的建议:

this.refs.updateTheWord.focus();

一起考虑的类似建议都没用。我甚至尝试愚弄 React,只是想看看我是否能做出什么来!我使用了真正的 DOM:

    const x = document.getElementById(this.props.word._id);
    x.focus();

但它也没有起作用。有一件事情甚至我都无法用语言表达,就像这个建议:将 ref 作为一个方法(我“猜测”)。我甚至没有尝试它,因为我有多个组件需要使用 ref 来获取每个组件的值,如果我的 ref 没有命名,我不知道如何获取值!

那么,请你给我一个思路,帮助我理解,如果我不使用表单(因为我需要一个单独的输入框来替换标签),当它的 CSS(Bootstrap)类失去“hidden”时,我如何设置焦点?

admin 更改状态以发布 2023年5月21日
0
0 Comments

只需为input添加autofocus属性即可。(当然在JSX中是autoFocus


0
0 Comments

您使用的ref方式并不是最优选,或者说不再是最佳实践。尝试使用以下方式:

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }
  focus() {
    this.textInput.current.focus();
  }
  render() {
    return (
         { this.textInput = input; }} />
        
    );
  }
}

更新:
自React 16.3版本起,您可以使用React.createRef() API。

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focus = this.focus.bind(this);
  }
  focus() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }
  render() {
    // tell React that we want to associate the  ref
    // with the `textInput` that we created in the constructor
    return (
        
        
    );
  }
}

自React 18.xx版本起,您可以使用useRef Hook。

import React, { useRef } from "react";
export const Form = () => {
  const inputRef = useRef(null);
  const focus = () => {
    inputRef.current.focus();
  };
  return (
      
      
  );
};

0