I am developing a react-native app. Recently, I encountered a strange behavior of functional components. Typically, I break large component into smaller components, write separate logic for each smaller component, and then call them in the same component.
In the below code, I have not defined the method onPressed
in the SmallComponentB
but when I click on this it calls the method from SmallComponentA
const SmallComponentA = ({}) => {
onPressed = () => alert('Clicked A')
return <Text onPress={onPressed} >Press On A</Text>
}
const SmallComponentB = ({}) => {
return <Text onPress={onPressed} >Press On B</Text>
}
const ActualComponent = ({}) => {
return(
<>
<SmallComponentA />
<SmallComponentB />
</>
)
}
2
Answers
So you can individually set the onPressed function inside each of the individual arrow function like,
You can do it both ways, either it’s a separate function in each or it should be a common function
With Separate
const SmallComponentA = ({}) => {
Common Function
const onPressed = ( component ) => alert(‘Common Clicked ‘+ component);
const SmallComponentA = ({}) => {
return <Text onPress={()=>onPressed("A")}>Press On A;
};
const SmallComponentB = ({}) => {
return <Text onPress={()=>onPressed("B")}>Press On B;
};
const ActualComponent = ({}) => {
return (
<>
</>
);
};
Hope it will hep you!