reactjs - ScrollView 不会使用 scrollTo() 水平移动
问题描述
我有以下水平滚动视图,我想滚动到 X 位置。
<ScrollView horizontal={true} ref={ref => this.scrollView = ref} showsHorizontalScrollIndicator={false}>
<TouchableOpacity onPress={() => {this.onPressDate(I18n.t("month1"))}} style={styles.month}>
<View style={{alignSelf: 'center' }}>
<Text style={[commonStyle.normalItemBold,{color:this.state.underlineMonth1?'#000':'#9B9B9B'}]}>{I18n.t("month1")}</Text>
<View style={[styles.rowSep, {opacity: this.state.underlineMonth1?100:0} ]}/>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this.onPressDate(I18n.t("month2"))}} style={styles.month}>
<View style={{alignSelf: 'center' }}>
<Text style={[commonStyle.normalItemBold,{color:this.state.underlineMonth2?'#000':'#9B9B9B'}]}>{I18n.t("month2")}</Text>
<View style={[styles.rowSep, {opacity: this.state.underlineMonth2?100:0} ]}/>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this.onPressDate(I18n.t("month3"))}} style={styles.month}>
<View style={{alignSelf: 'center' }}>
<Text style={[commonStyle.normalItemBold,{color:this.state.underlineMonth3?'#000':'#9B9B9B'}]}>{I18n.t("month3")}</Text>
<View style={[styles.rowSep, {opacity: this.state.underlineMonth3?100:0} ]}/>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this.onPressDate(I18n.t("month4"))}} style={styles.month}>
<View style={{alignSelf: 'center' }}>
<Text style={[commonStyle.normalItemBold,{color:this.state.underlineMonth4?'#000':'#9B9B9B'}]}>{I18n.t("month4")}</Text>
<View style={[styles.rowSep, {opacity: this.state.underlineMonth4?100:0} ]}/>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this.onPressDate(I18n.t("month5"))}} style={styles.month}>
<View style={{alignSelf: 'center' }}>
<Text style={[commonStyle.normalItemBold,{color:this.state.underlineMonth5?'#000':'#9B9B9B'}]}>{I18n.t("month5")}</Text>
<View style={[styles.rowSep, {opacity: this.state.underlineMonth5?100:0} ]}/>
</View>
</TouchableOpacity>
</ScrollView>
我在 ComponentDidMount() 中使用了 scrollTo ,但它没有用,并且 scrollView 没有找到移动的位置。这是代码:
componentDidMount=()=>{
this.scrollView.scrollTo({ X:0, Y:100 });
}
你能帮我解决问题吗?
解决方案
scrollTo({x: 0, y: 0, animated: true})
使用该方法可以实现滚动到某个位置。
只需设置 ax: 水平滚动的值或 y: 垂直滚动的值。
在您的情况下,它应该是:
scrollTo({x: 100, y: 0, animated: true})