xxxxxxxxxx
const Container = React.forwardRef((props, ref) => {
return <div ref={ref}>{props.children}</div>
})
const App = () => {
const elRef = React.useRef();
React.useEffect(() => {
console.log(elRef);
elRef.current.style.background = 'lightblue';
}, [elRef])
return (
<Container ref={elRef}/>
);
xxxxxxxxxx
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
xxxxxxxxxx
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button, TouchableOpacity } from 'react-native';
import React from 'react';
export default function App() {
function q()
{
console.log(hello.current.props.title);
}
const hello = React.createRef();
return (
<View style={styles.container}>
<TouchableOpacity onPress={()=>q()}>
<Text>
Invoke Fancy Button
</Text>
</TouchableOpacity>
<FancyButton ref={hello}/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
const FancyButton = React.forwardRef((props, ref) => (
<Button ref={ref} id="myId" title="FancyButton" />
));
xxxxxxxxxx
In React, parent components typically use props to transfer data down to their children.
Consider you make a child component with a new set of props to change its behavior.
We need a way to change the behavior of a child component without having to look for
the state or re-rendering the component. We can do this by using refs.
We can access a DOM node that is represented by an element using refs.
As a result, we will make changes to it without affecting its state or having to re-render it.
When a child component needs to refer to its parent’s current node, the parent component
must have a way for the child to receive its ref. The technique is known as ref forwarding.
-------------------------------------------------------------------------------------------
Syntax:
React.forwardRef((props, ref) => {})