React Native ScrollView snapping back to top after

2020-07-03 04:10发布

I have used ScrollView in other apps adding just a style={styles.container} with the styles. However in this app I am creating in my styles I have alignItems:'flex-start' which throws an error with just style={styles.container} and instead you need to pass in alignItems:'flex-start' through contentContainerStyle={styles.container}.

Error: Invariant Violation: ScrollView child layout (["alignItems"]) must by applied through the contentContainerStyle prop.

However when I add contentContainerStyle when scrolling down in the view, once the finger is lifted off the phone (or release of the mouse in simulator), the scroll automatically goes back to the top. If I just use style={styles.container} and take out the alignItems:'flex-start' it scrolls correctly, but my items in the UI are not laid out how I need them. What is causing it to scroll back to the top with contentContainerStyle and is there a fix?

render:

var _that = this;
var iconsToShow = icons.map(function (icon, i){
  if(i < 81){
    return (
      <TouchableHighlight
        onPress={() => _that.changeIcon(indexToChange, icon)}
        underlayColor='#F7F7F7'
        key={i}>
          <Text style={styles.iconText}><IonIcons name={icon} size={30} color="#555" /></Text>
      </TouchableHighlight>
    );
  }
});

return (
  <Carousel width={SCREEN_WIDTH} animate={false} indicatorColor="#444" inactiveIndicatorColor="#999" indicatorAtBottom={false} indicatorOffset={16}>
    <View>
      <ScrollView contentContainerStyle={styles.container}>{iconsToShow}</ScrollView>
    </View>

    <View>
      //next page for carousel
    </View>

  </Carousel>
);

2条回答
家丑人穷心不美
2楼-- · 2020-07-03 04:16

If someone still couldn't fix the problem, try put {flex: 1} into "all" parents of the ScrollView

查看更多
小情绪 Triste *
3楼-- · 2020-07-03 04:17

I figured out how to get it to scroll. Instead of having the View wrapping the ScrollView and the ScrollView having any flex styling or alignItems:'flex-start' with contentContainerStyle={styles.container}, put that on the View which is a child of the ScrollView and just use style= instead of contentContainerStyle=.

render:

<ScrollView style={styles.container}>
    <Text style={styles.goalName}>{goal}</Text>
    <View style={styles.viewContainer}>
        {iconsToShow}
    </View>
</ScrollView>

Styling:

var styles = StyleSheet.create({
    container: {
        backgroundColor: 'transparent',
        paddingLeft:20,
        paddingRight:20
    },
    viewContainer:{
        flexDirection:'row',
        flexWrap: 'wrap',
        alignItems: 'flex-start',
        flex: 1
    },
    iconText:{
        paddingLeft:15,
        paddingRight:15,
        paddingTop:15,
        paddingBottom:15
    },
    goalName:{
        textAlign:'center',
        marginTop:40,
        marginBottom:10,
        fontSize:20
    }
});
查看更多
登录 后发表回答