【问题标题】:Reactjs focus an input field located in a child component which is inside another child componentReactjs 聚焦位于另一个子组件内的子组件中的输入字段
【发布时间】:2018-06-16 20:37:13
【问题描述】:

我目前正在尝试关注位于另一个子组件内的子组件中的输入字段。考虑以下,

父.js

child1.js

child2.js

当从 parent.js 中单击按钮时,我想将输入字段聚焦在 child2 中。

【问题讨论】:

    标签: reactjs input


    【解决方案1】:

    我并不是说使用这种技术很好,但您可以通过创建一个 setRef 函数来实现这一点,该函数将孩子 1 传递给孩子 2。请务必阅读此https://reactjs.org/docs/refs-and-the-dom.html 为什么 refs 不是最好的东西.对我来说,我会使用道具回调。

    但如果你真的想使用 ref 这就是你可以做到的。我把代码示例放在这里。你也可以在这里玩代码https://codesandbox.io/s/5x8530j3xn

    class Child2 extends React.Component {
      render() {
        return (
          <div>
            <input ref={this.props.setRef} />
          </div>
        );
      }
    }
    
    class Child1 extends React.Component {
      render() {
        return (
          <div>
            <Child2 setRef={this.props.setRef} />
          </div>
        );
      }
    }
    
    class Parent extends React.Component {
      setRef = ref => {
        this.input = ref;
      };
    
      focus = () => {
        this.input.focus();
      };
    
      render() {
        return (
          <div>
            <Child1 setRef={this.setRef} />
            <button onClick={this.focus}>Go Focus</button>
          </div>
        );
      }
    }
    

    【讨论】:

    • 什么是可用于 ref 的 proptype。谢谢。
    【解决方案2】:

    只需在 React 方法中使用普通的 JavaScript。

    handleFocus () {
      document.getElementById('inputField').focus()
    }
    
    <button onClick={this.handleFocus}>My Button</Button>
    

    这将在单击按钮后聚焦输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 2018-10-04
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多