我正在尝试使用 React Native 中的水平 ScrollView 对于 Android,起始位置在滚动图像的中间而不是 (0,0)。scrollTo
方法似乎在 componentDidMount
内部被正确调用但应用程序中没有任何移动,它仍然显示为一直向左滚动。
根据文档,由于这是 Android,我无法访问 contentOffset Prop ,或者我会直接设置它。这是代码:
'use strict';
var React = require('react-native');
var {
StyleSheet,
View,
Text,
ScrollView,
Component,
} = React;
var precomputeStyle = require('precomputeStyle');
class Carousel extends Component {
constructor(props, context) {
super(props, context);
//this.changeContent = this.changeContent.bind(this);
}
componentDidMount() {
this.myScroll.scrollTo(100);
console.log("called DidMount");
}
render() {
return (
<View style={{flex: 1}}>
<ScrollView ref={(ref) => this.myScroll = ref}
contentContainerStyle={styles.container}
horizontal={true}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
bounces={true}
onMomentumScrollEnd={this.onAnimationEnd}
>
{this.props.children}
</ScrollView>
</View>
);
}
onAnimationEnd(e) {
console.log("curr offset: " + e.nativeEvent.contentOffset.x);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
page: {
alignItems: 'center',
justifyContent: 'center',
borderWidth: 1,
},
});
module.exports = Carousel;
请您参考如下方法:
我有同样的问题,浪费了几个小时没有它:
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// Call with the present values in order to re-layout if necessary
scrollTo(getScrollX(), getScrollY());
}
所以,你必须在动画之后延迟它
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
this.myScroll.scrollTo(100);
console.log("called DidMount");
})
}