[英]React / React Native: How do I use callback ref in functional component?
在这个库中: https://github.com/wix/react-native-keyboard-aware-scrollview
从自述文件中引用的这两行代码( TextInput 组件的 Auto-Scrolling部分),父组件可以使用回调 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
。 在父滚动视图和子输入是功能组件的情况下,我该如何做同样的事情?
没有必要以此为例,但使用它会很棒。
任何概念证明都值得赞赏。
这是在功能组件中使用 refs 的示例。
const MyComponent = () => {
const textRef = React.useRef();
return (
<KeyboardAwareScrollView getTextInpurRefs={() => [textRef]}>
<TextInput ref={textRef} />
</KeyboardAwareScrollView>
)
}
您可以使用useRef
挂钩。
例如:
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.