寫項目的時候碰到this對象錯誤,具體報錯為
error
解決辦法.
原因是this對象和state的this對象不是同一個所致。將其修改為同一個就可以了
constructor(props){
super(props);
this.state={
indexPage:0,
};
}
render() {
return (
<View style={styles.container}>
{/*上面的滾動部分*/}
<ScrollView
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
horizontal={true}
onMomentumScrollEnd = {this.onScrollAnimationEnd}
>
{this.renderTopScrollItem()}
</ScrollView>
</View>
);
}
//當滾動動畫結束之后調用此回調
//如果出于某些原因想使用瀏覽器原生事件,可以使用 nativeEvent 屬性獲取
//contentOffset 用來手動設置初始的滾動坐標
onScrollAnimationEnd(e){
var currPage = Math.floor(e.nativeEvent.contentOffset.x/width);
this.setState({
indexPage:currPage
});
}
修改
constructor(props){
super(props);
self = this,// self = this;//為了防止this.setState的this對象不一致
self.state={
indexPage:0,
};
}
render() {
return (
<View style={styles.container}>
{/*上面的滾動部分*/}
<ScrollView
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
horizontal={true}
onMomentumScrollEnd = {this.onScrollAnimationEnd}
>
{this.renderTopScrollItem()}
</ScrollView>
</View>
);
}
//當滾動動畫結束之后調用此回調
//如果出于某些原因想使用瀏覽器原生事件,可以使用 nativeEvent 屬性獲取
//contentOffset 用來手動設置初始的滾動坐標
onScrollAnimationEnd(e){
var currPage = Math.floor(e.nativeEvent.contentOffset.x/width);
self.setState({//和state的this一致
indexPage:currPage
});
}