【问题标题】:In React Native, how can I get the Y offset of a custom component and then scroll a ScrollView to its position?在 React Native 中,如何获取自定义组件的 Y 偏移量,然后将 ScrollView 滚动到其位置?
【发布时间】:2016-05-26 02:15:58
【问题描述】:

在 React Native 中,我有一个带有 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>
  );
};

MyButton 是这样定义的:

function MyButton(props) {
  return (
    <TouchableHighlight onPress={props.onPress}>
      <Text>Press Me</Text>
    </TouchableHighlight>
  );
}

我想要完成的是,当用户按下MyButton 组件时,ScrollView 应该滚动以便MyComponent2 可见。问题是我不能在自定义组件上使用measure,只能直接在View中使用。

所以我的问题是:获取自定义 React Native 组件的 Y 偏移量的最佳方法是什么?

【问题讨论】:

    标签: javascript uiscrollview react-native scrollview


    【解决方案1】:

    我最终将我的组件包裹在一个额外的 View 周围,以便能够获得它的偏移量:

    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>
      );
    };
    

    【讨论】:

    • 对于我添加了ref 的视图,我没有得到正确的pageOffsetY 位置值。你对此有什么想法吗?
    • check my post 告诉我您的建议。
    猜你喜欢
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2018-03-22
    • 2021-07-27
    • 2020-09-21
    相关资源
    最近更新 更多