当组件中有多个输入时,如何在 ReactJS 中关注输入字段?

How to focus on an input field in ReactJS when there are multiple inputs in the component?

我正在开发 ReactJS 应用程序。我有一个生成 HTML table 的组件。使用 Map 子组件用于为 table 生成行。每行包含一定数量的输入字段。

编辑输入字段时,在某些情况下会在父组件中触发模态 window。模态让用户可以选择三个按钮来点击。单击模式中的特定按钮时,我希望焦点 return 到用户正在编辑的输入字段。

任何人都可以给我一些关于如何实现这一目标的指示吗?

我研究过使用 refs,但我看到的所有示例都使用具有一个输入的组件进行了演示。因为模态是从父组件触发的,所以我很难理解如何 use/get 来自子组件的引用。

感谢任何帮助。

I want the focus to return to the input field the user was editing.

您有多个输入框,您希望专注于某个输入框。为了能够做到这一点,您需要多个 refs --12 refs in your case--.

  1. 像这样定义你的引用:

    const inputRef = useRef([]);
    
  2. 您需要将输入节点分配给 ref 数组。如果您使用某种循环来生成输入字段,您可以这样做:

    <input ref={el => inputRef.current[i] = el} />
    
  3. 现在,您需要一个变量来存储当前正在编辑的输入的索引。

  4. 最后,您可以使用这个保存最后编辑的输入字段索引的变量来实现您想要的效果:

    inputRef.current[i].focus()
    

如果您使用 class 个组件:

  1. 在你的构造函数中定义一个数组:

    this.myRefs = []
    
  2. 像这样分配 HTML 个节点:

    <input ref={el => this.myRefs[i] = el} />
    
  3. 这一步不变。

  4. 现在您可以像这样聚焦特定的输入元素:

    this.myRefs[i].focus()
    

以@user9408899 的回答为指导并阅读,我想出了以下解决方案(仅显示与该解决方案直接相关的部分代码)。

父组件

  • 实现了 inputRefToFocus 属性 来存储我们的 ref 想添加焦点。
  • 实现setInputRefToFocus(ref)赋值状态上面的属性,也将this和inputRefToFocus传递给子组件
    export class Parent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          ...
          // this is the ref for the input field to focus on
          // when modal window appears, depending on button clicked,
          // we want to focus on the field user was editing
          inputRefToFocus: null
        };

        this.setInputRefToFocus = this.setInputRefToFocus.bind(this);
      }

      setInputRefToFocus(ref) {
        this.setState({ inputRefToFocus: ref });
      }

      render() {
        { rows.map(elem => (
          <PivotTableRow
            setInputRefToFocus={this.setInputRefToFocus}
            inputRefToFocus={this.state.inputRefToFocus}
          />
        )) }
      }
    }

子组件

  • 创建输入元素时,每个元素都会添加到引用数组中。

  • 当input获得焦点时,我们在父组件的inputRefToFocus中设置它的ref 属性.

  • 将焦点设置在componentDidUpdate()
export class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      ...
    };

    this.inputRef = [];

  }

  componentDidUpdate(prevProps) {
    if (this.props !== prevProps) {
      if (this.inputRef[this.props.inputRefToFocus] !== undefined) {
        this.inputRef[this.props.inputRefToFocus].focus();
      }
    }
  }

  render() {
    return (
      // loop to generate input elements
      <Input
        ref={el => { this.inputRef[dummyvalue] = el; }
        onChange={...}
        onFocus={() => this.props.setInputRefToFocus(dummyvalue)}
      /> 
    );
  }
}

我觉得代码可以显着改进,因为这是我第一次尝试它