【问题标题】:React / React Native: How do I use callback ref in functional component?React / React Native:如何在功能组件中使用回调引用?
【发布时间】:2020-08-12 00:14:13
【问题描述】:

在这个库中:https://github.com/wix/react-native-keyboard-aware-scrollview

从自述文件中引用的这两行代码(TextInput 组件的自动滚动部分),父组件可以使用回调 ref 技术获取子组件的 ref 数组:

<KeyboardAwareScrollView 
    style={styles.container} 
    getTextInputRefs={() => { return [this._textInputRef];}}
>
    <TextInput 
        style={styles.textInput} 
        placeholder={'My Input'} 
        ref={(r) => { this._textInputRef = r; }}
    />

</KeyboardAwareScrollView>

getTextInputRefs 是一个回调,您可以在其中返回一组对位于 scrollView 内的子 TextInput 组件的引用。

但是,据我所知,在功能组件中没有像 this._textInputRef 这样的东西。在父滚动视图和子输入是功能组件的情况下,我该如何做同样的事情?

没必要用这个作为例子,但是用起来会很好。

感谢任何概念证明。

【问题讨论】:

    标签: reactjs react-native react-ref


    【解决方案1】:

    这是一个在函数式组件中使用 refs 的示例。

    const MyComponent = () => {
      const textRef = React.useRef();
    
      return (
        <KeyboardAwareScrollView getTextInpurRefs={() => [textRef]}>
          <TextInput ref={textRef} />
        </KeyboardAwareScrollView>
      )
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用useRef hook。

      例如:

      export default () => {
          const textInputRef = React.useRef(null);
          return (
              <KeyboardAwareScrollView 
                  style={styles.container} 
                  getTextInputRefs={() => { return [textInputRef];}}
              >
                  <TextInput 
                      style={styles.textInput} 
                      placeholder={'My Input'} 
                      ref={textInputRef}
                  />
              </KeyboardAwareScrollView>
          );
      }
      

      【讨论】:

        猜你喜欢
        • 2021-07-15
        • 2019-01-07
        • 2021-06-14
        • 1970-01-01
        • 2020-09-10
        • 2017-09-16
        • 2021-02-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多