如何找到焦点 React 组件?(如 document.activeElement)

Slb*_*box 8 javascript focus reactjs react-dom

如果您有 500 个组件,每个组件都有一个ref,您将如何找到用户关注的组件?所有带有 的组件ref都是可聚焦的元素,例如<input /><textarea />等。为简单起见,所有这些refs都可以从单个顶级组件访问。

如果您的 React 组件具有,这非常简单classNames- 但是如果您想找到refa 的document.activeElement,是否有某种方法可以实现这一目标而不必求助于 classNames?

为了说明为什么我们没有classNames,我们正在使用JSSvia emotion。为了className这个目的而必须手动分配所有东西是相当荒谬的。我没有想到明显的替代方案。

Chr*_* B. 14

这可能是一个很好的用例,自定义钩子挂接到本机 DOM 方法中以跟踪焦点事件,然后返回活动元素。这将在每次新元素获得焦点时记录活动元素:

const useActiveElement = () => {
  const [active, setActive] = React.useState(document.activeElement);
  
  const handleFocusIn = (e) => {
    setActive(document.activeElement);
  }
  
  React.useEffect(() => {
    document.addEventListener('focusin', handleFocusIn)
    return () => {
      document.removeEventListener('focusin', handleFocusIn)
  };
  }, [])
  
  return active;
}

const App = () => {
  const focusedElement = useActiveElement();
  
  React.useEffect(() => {
     if (focusedElement) {
       focusedElement.value && console.log(focusedElement.value);
     }
    console.log(focusedElement);
  }, [focusedElement])
  
  return (
    <div>
        <input type="text"/>
        <button>Button</button>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

但是,将此元素与您的 ref 相关联可能会很棘手,因为您需要保留一组 ref 以进行搜索,这可能涉及为每个元素提供自己的回调 ref以存储在 Array 或类似的东西中。但是根据您在元素聚焦后需要对它做什么,它可能没有必要。例如,我上面发布的代码将记录输入的值(如果存在)。更具体地了解您用于跟踪此数据的用例会有所帮助。


tar*_*ziz 2

你想要这样的东西吗,React 为你提供了使用ref进行跟踪/聚焦的选项

import React, { Component } from "react";

class App extends Component {

constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.button = React.createRef();
    this.textarea = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
}

focusTextInput() {
    // this.textInput.current.focus();
    this.button.current.focus();
    // this.textarea.current.focus();
}

render() {
    return (
    <div>
        <input type="text" ref={this.textInput} />
        <button ref={this.button}>something</button>
        <textarea ref={this.textarea}></textarea>
        <input
              type="button"
              value="Focus the text input"
              onClick={this.focusTextInput}
        />
    </div>
    );
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

您可以在这里获取详细信息