寫項(xiàng)目的時(shí)候碰到this對(duì)象錯(cuò)誤德迹,具體報(bào)錯(cuò)為
error
解決辦法.
原因是this對(duì)象和state的this對(duì)象不是同一個(gè)所致芽卿。將其修改為同一個(gè)就可以了
constructor(props){
super(props);
this.state={
indexPage:0,
};
}
render() {
return (
<View style={styles.container}>
{/*上面的滾動(dòng)部分*/}
<ScrollView
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
horizontal={true}
onMomentumScrollEnd = {this.onScrollAnimationEnd}
>
{this.renderTopScrollItem()}
</ScrollView>
</View>
);
}
//當(dāng)滾動(dòng)動(dòng)畫結(jié)束之后調(diào)用此回調(diào)
//如果出于某些原因想使用瀏覽器原生事件,可以使用 nativeEvent 屬性獲取
//contentOffset 用來手動(dòng)設(shè)置初始的滾動(dòng)坐標(biāo)
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對(duì)象不一致
self.state={
indexPage:0,
};
}
render() {
return (
<View style={styles.container}>
{/*上面的滾動(dòng)部分*/}
<ScrollView
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
horizontal={true}
onMomentumScrollEnd = {this.onScrollAnimationEnd}
>
{this.renderTopScrollItem()}
</ScrollView>
</View>
);
}
//當(dāng)滾動(dòng)動(dòng)畫結(jié)束之后調(diào)用此回調(diào)
//如果出于某些原因想使用瀏覽器原生事件胳搞,可以使用 nativeEvent 屬性獲取
//contentOffset 用來手動(dòng)設(shè)置初始的滾動(dòng)坐標(biāo)
onScrollAnimationEnd(e){
var currPage = Math.floor(e.nativeEvent.contentOffset.x/width);
self.setState({//和state的this一致
indexPage:currPage
});
}