【问题标题】:React Native - How to get Y Offset Value of a view from ScrollView?React Native - 如何从 ScrollView 获取视图的 Y 偏移值?
【发布时间】:2018-11-11 09:17:37
【问题描述】:

我正在尝试获取视图的滚动位置。但是 Y 到页面的偏移量 的值与视图的位置无关。

ScrollView 层次结构:

<ScrollView>
  - MyComponent1
  - MyComponent2
    - SubView1
       - SubView2
         - <View> (Added ref to this view and passing Y offset value through props)
  - MyComponent3
 </ScrollView>

SubView2 组件:

this.myComponent.measure( (fx, fy, width, height, px, py) => {
   console.log('Component width is: ' + width)
   console.log('Component height is: ' + height)
   console.log('X offset to frame: ' + fx)
   console.log('Y offset to frame: ' + fy)
   console.log('X offset to page: ' + px)
   console.log('Y offset to page: ' + py)

   this.props.moveScrollToParticularView(py)
})

<View ref={view => { this.myComponent = view; }}>

我在onScroll 方法上检查了SubView2 视图的确切位置。但确实与measure value 匹配。我可以弄清楚measure value 是错误的。

是不是ScrollView层次问题?

【问题讨论】:

    标签: javascript react-native uiscrollview scrollview


    【解决方案1】:

    View 组件有一个名为onLayout 的属性。您可以使用此属性来获取该组件的位置。

    onLayout

    在装载和布局更改时调用:

    {nativeEvent: { layout: {x, y, width, height}}}
    

    计算完布局后立即触发此事件, 但当时新的布局可能还没有体现在屏幕上 接收到事件,尤其是在布局动画处于 进展。

    更新

    onLayout prop 给父组件一个位置。这意味着要找到SubView2的位置,你需要得到所有父组件的总和(MyComponent2 + SubView1 + SubView2)。

    示例

    export default class App extends Component {
      state = {
        position: 0,
      };
      _onLayout = ({ nativeEvent: { layout: { x, y, width, height } } }) => {
        this.setState(prevState => ({
          position: prevState.position + y
        }));
      };
      componentDidMount() {
        setTimeout(() => {
          // This will scroll the view to SubView2
          this.scrollView.scrollTo({x: 0, y: this.state.position, animated: true})
        }, 5000);
      }
      render() {
        return (
          <ScrollView style={styles.container} ref={(ref) => this.scrollView = ref}>
            <View style={styles.view}>
              <Text>{'MyComponent1'}</Text>
            </View>
            <View style={[styles.view, { backgroundColor: 'blue'}]} onLayout={this._onLayout}>
              <Text>{'MyComponent2'}</Text>
              <View style={[styles.view, , { backgroundColor: 'green'}]} onLayout={this._onLayout}>
                <Text>{'SubView1'}</Text>
                <View style={[styles.view, { backgroundColor: 'yellow'}]} onLayout={this._onLayout}>
                  <Text>{'SubView2'}</Text>
                </View>
              </View>
            </View>
          </ScrollView>
        );
      }
    } 
    

    【讨论】:

    • 是的。也试过onLayout。实际上,Y value 对于subview2 是 0。如果我在MyComponent2 上添加参考,我将获得 Y 值
    • 是的。我想需要添加每个父母。让我试试这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多