Bal*_*ian 9 javascript scrollview uiscrollview react-native
我试图获得视图的滚动位置.但Y偏移到页面的值与视图的位置无关.
ScrollView层次结构:
<ScrollView>
- MyComponent1
- MyComponent2
- SubView1
- SubView2
- <View> (Added ref to this view and passing Y offset value through props)
- MyComponent3
</ScrollView>
Run Code Online (Sandbox Code Playgroud)
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; }}>
Run Code Online (Sandbox Code Playgroud)
我检查了方法SubView2视图的确切位置onScroll.但确实与之匹配measure value.我可以弄明白measure value是错的.
它是ScrollView层次结构问题吗?
View组件具有名为的属性onLayout。您可以使用此属性获取该组件的位置。
onLayout
通过以下方式调用安装和布局更改:
Run Code Online (Sandbox Code Playgroud){nativeEvent: { layout: {x, y, width, height}}}一旦计算出布局,就会立即触发此事件,但是在接收到事件时,新的布局可能尚未反映在屏幕上,特别是在进行布局动画时。
更新资料
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5208 次 |
| 最近记录: |