我已经查看了许多文档和示例,但我似乎仍然不太明白如何forwardRef
在 React Native 中使用带有 TypeScript 的功能组件。下面是一个示例,其中我创建了MyCustomComponent
一个自定义函数,我尝试通过创建引用从父级调用该函数。但是,由于 ref 定义不正确null
,我显然收到一条错误消息,告诉我该函数不存在。请帮助我了解如何forwardRef
在 React Native 中正确使用。提前致谢!
interface MyCustomComponentProps {
title: string
}
const MyCustomComponent: React.FunctionComponent<MyCustomComponentProps> = React.forwardRef((props, ref) => {
const coolAlert = () => {
Alert.alert('Hey!', 'This was called from MyCustomComponent')
}
return (
<View>
<Text>{props.title}</Text>
</View>
)
})
export default function App () {
const MyCustomComponentRef = useRef()
return (
<SafeAreaView>
<MyCustomComponent ref={MyCustomComponentRef} title='Hello World' />
<TouchableOpacity
onPress={() => {
MyCustomComponentRef.coolAlert()
}}>
<Text>Click Me</Text>
</TouchableOpacity>
</SafeAreaView>
)
}