gpt4 book ai didi

javascript - React Native - 如何从 ScrollView 获取 View 的 Y 偏移值?

转载 作者:数据小太阳 更新时间:2023-10-29 03:53:21 27 4
gpt4 key购买 nike

我正在尝试获取 View 的滚动位置。但是 Y offset to page 的值与 View 的位置无关。

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 View 的确切位置。但与 measure value 匹配。我可以弄清楚 measure value 是错误的。

是不是ScrollView层级问题?

最佳答案

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

onLayout

Invoked on mount and layout changes with:

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

This event is fired immediately once the layout has been calculated, but the new layout may not yet be reflected on the screen at the time the event is received, especially if a layout animation is in progress.

更新

onLayout 属性给父组件一个位置。这意味着要找到 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>
);
}
}

关于javascript - React Native - 如何从 ScrollView 获取 View 的 Y 偏移值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50639892/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com