问题
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?
回答1:
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>
);
};
来源:https://stackoverflow.com/questions/37450468/in-react-native-how-can-i-get-the-y-offset-of-a-custom-component-and-then-scrol