【问题标题】:React Native: How to focus a TextInput wrapped in a custom component?React Native:如何聚焦包装在自定义组件中的 TextInput?
【发布时间】:2020-09-05 15:15:32
【问题描述】:

在我的 React Native 应用程序中,我有一个包含 TextInput 的自定义组件。在使用自定义组件的代码中,我想在TextInput 上调用.focus()。我尝试像这样直接在自定义组件上调用它:

<CustomComponent
  ref={ref => {
    this.customComponent = ref;
  }}
/>

this.customComponent.focus();

但我不能,因为我认为自定义组件没有focus() 方法。我可以找到一种在包装好的TextInput 上调用它的方法,但我想知道是否有一种方法可以直接在自定义组件上调用它。

有人知道我该如何处理吗?

【问题讨论】:

  • 可以在CustomComponent中定义焦点函数,调用TextInput的焦点函数。

标签: reactjs react-native focus textinput


【解决方案1】:

如果是类组件,您可以使用CustomComponent.prototype.yourFunction()

youFunction 使用 ref 在TextInput 上调用focus()

【讨论】:

    【解决方案2】:

    如果 CustomComponent 是您自己的组件,那么在这种情况下,您可以通过 Forwarding Refs 传递 ref:


    这里我创建了示例代码 sn-ps,它在 CustomComponent 内部有输入,我们可以通过 React.forwardRef((props, ref) 访问该组件内部的 ref

    然后我们有来自父组件的createRef 并像&lt;CustomComponent ref={this.ref}&gt; 一样传递引用。

    希望这会对你有所帮助。

    const CustomComponent = React.forwardRef((props, ref) => (
      <div>
        <input type="text" ref={ref} />
      </div>
    ));
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.ref = React.createRef();
      }
      componentDidMount() {
        if(this.ref.current) {
          this.ref.current.focus();
        }
      }
      
      render() {
        return (
          <div>
            Get Focused : 
            <CustomComponent ref={this.ref} />
          </div>
        );
      }
      
    }
    
    ReactDOM.render(<App />, document.getElementById('react-root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
    <div id="react-root"></div>

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 2017-07-11
      • 2022-07-06
      • 2018-08-07
      • 2021-11-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多