In React Native, how can I get the Y offset of a custom component and then scroll a ScrollView to its position?

倾然丶 夕夏残阳落幕 提交于 2021-02-19 09:13:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!