In React Native, I have a screen with a ScrollView
:
let scrollView;
let myComponent2;
function onPress() {
myComponent2.measure((frameOffsetX, frameOffsetY, width, height, pageOffsetX, pageOffsetY) => {
scrollView.scrollTo({ y: frameOffsetY });
}
function MyScrollView() {
return (
<ScrollView ref={ref => scrollView = ref}>
<MyButton onPress={onPress} />
<MyComponent1 />
<MyComponent2 ref={ref => myComponent2 = ref} />
<MyComponent3 />
</ScrollView>
);
};
And MyButton
is defined like this:
function MyButton(props) {
return (
<TouchableHighlight onPress={props.onPress}>
<Text>Press Me</Text>
</TouchableHighlight>
);
}
What I'm trying to accomplish is that when the user presses on the MyButton
component, the ScrollView
should scroll so that MyComponent2
is visible. The problem is that I can't use measure
on a custom component, only directly in a View
.
So my question is: what would be the best approach to get the Y offset of a custom React Native component?
I ended up wrapping my component around an extra View
to be able to get its offset:
let scrollView;
let myComponent2Wrapper;
function onPress() {
myComponent2Wrapper.measure((frameOffsetX, frameOffsetY, width, height, pageOffsetX, pageOffsetY) => {
scrollView.scrollTo({ y: frameOffsetY });
}
function MyScrollView() {
return (
<ScrollView ref={ref => scrollView = ref}>
<MyButton onPress={onPress} />
<MyComponent1 />
<View ref={ref => myComponent2Wrapper = ref}>
<MyComponent2 />
</View>
<MyComponent3 />
</ScrollView>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.