Reputation: 947
I want to call the onPress()
method of my Pressable. How can I achieve this? I tried calling the onPress()
method when I hit the second button via a ref but it did not work.
const pressableRef = useRef(null);
return (
<Pressable
style={{ width: 100, height: 100, backgroundColor: 'yellow' }}
onPress={() => console.log('I want to print this')}
ref={pressableRef}
/>
<Button
title="Klick me"
onPress={() => {pressableRef.current.onPress()}
/>
);
Upvotes: 1
Views: 1407
Reputation: 621
my code not work in this situation, but i do some changes and it works for me :)
this is my code:
const ElementRef = createRef();
useEffect(() => {
if (ElementRef.current) {
setTimeout(() => {
ElementRef.current?.scrollToIndex({
index: 3,
animated: true
})
}, 500);
}
}, [ElementRef])
// ...
<FlatList
nestedScrollEnabled
data={Calendar}
keyExtractor={item => item.visit_day_identity}
renderItem={renderItem}
horizontal
showsHorizontalScrollIndicator={false}
snapToEnd
ref={ElementRef}
/>
Upvotes: 0
Reputation: 941
There is no method with the name onPress on Pressable Component that you can call by reference. onPress is a prop you pass to the Pressable that accepts a function.
You can define a function before return so it can be available by both.
Try this
const callPressableFunc = () => {
console.log('I want to print this');
};
return (
<View>
<Pressable
style={{width: 100, height: 100, backgroundColor: 'yellow'}}
onPress={callPressableFunc}
ref={pressableRef}
/>
<Button title="Klick me" onPress={callPressableFunc} />
</View>
);
Upvotes: 1