React / React Native:如何在函数组件中使用回调引用?

3
在这个库中: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这样的东西。如果父scrollview和子输入都是功能性组件,则如何实现相同的功能?

不一定要使用此示例,但最好使用它。

任何概念验证都将受到赞赏。

2个回答

0
这是一个在函数组件中使用 refs 的示例。
const MyComponent = () => {
  const textRef = React.useRef();

  return (
    <KeyboardAwareScrollView getTextInpurRefs={() => [textRef]}>
      <TextInput ref={textRef} />
    </KeyboardAwareScrollView>
  )
}

0
你可以使用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>
    );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接