Last active
July 20, 2022 19:29
-
-
Save mfazekas/83c8705baa80f3b20c2e4f720be1ebf7 to your computer and use it in GitHub Desktop.
ComponentFC useRef
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable react-native/no-inline-styles */ | |
import React, { | |
Component, | |
useRef, | |
useImperativeHandle, | |
forwardRef, | |
} from 'react'; | |
import { View, Button, Text } from 'react-native'; | |
class ComponentC extends React.Component<{ name: string }> { | |
doSomething() { | |
console.log(' => ComponentC.doSomething'); | |
} | |
render() { | |
return ( | |
<View> | |
<Text>{this.props.name}</Text> | |
</View> | |
); | |
} | |
} | |
type ComponentFCRef = { | |
doSomething(): void; | |
}; | |
interface ComponentFCProps { | |
name: string; | |
} | |
const ComponentFC = forwardRef<ComponentFCRef, ComponentFCProps>(function ( | |
props: { name: string }, | |
ref: React.Ref<ComponentFCRef>, | |
): JSX.Element { | |
useImperativeHandle(ref, () => ({ | |
doSomething: () => { | |
console.log(' => ComponentFC.doSomething'); | |
}, | |
})); | |
return ( | |
<View> | |
<Text>{props.name}</Text> | |
</View> | |
); | |
}); | |
type ComponentFC = ComponentFCRef; | |
export default function RefExample() { | |
const componentCRef = useRef<ComponentC>(null); | |
const componentFCRef = useRef<ComponentFC>(null); | |
return ( | |
<View | |
style={{ backgroundColor: 'white', flex: 1, padding: 20, margin: 20 }} | |
> | |
<ComponentC name="Component1" ref={componentCRef} /> | |
<ComponentFC name="Component1" ref={componentFCRef} /> | |
<Button | |
title="try" | |
onPress={() => { | |
console.log(' => try pressed'); | |
componentCRef.current?.doSomething(); | |
componentFCRef.current?.doSomething(); | |
}} | |
/> | |
</View> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment