javascript - 在子组件中定义方法以使用 ref 挂钩 - 反应原生功能组件
问题描述
我有 2 个功能组件,比如说Parent
和Child
. 然后我在组件doThis()
内部有一个方法Child
来调用某些功能,例如子状态更新。Child
组件在父级内部,我需要使用useRef()
钩子将其用作引用并调用该doThis()
函数。
实现是这样的。
//Component Parent
function Parent(){
const child= useRef()
if(child.current){
child.current.doThis()
}
return( <Child ref={child}/>)
}
function Child({ref}){
// Don't know how to define
function doThis(){
//Do some task
}
return( <View/>)
}
我在 react-native 文档中看到了一个名为Methods的部分。例如:scrollToIndex()
在FlatList
那么如何使用功能组件来定义这样的方法呢?
解决方案
此类组件的示例:
import { TextInput as TextInputNative } from "react-native";
import React from "react";
const TextInput = React.forwardRef(
({ ...props }, ref) => (
<TextInputNative
ref={ref}
{...props}
/>
)
);
export default TextInput;
下面我如何在代码中使用我的组件:
<TextInput
ref={inputRef}
/>
要创建一个 ref,我使用useRef(null);