React-Native | ScrollView right to left

2020-07-09 08:16发布

问题:

I've got Simple ScrollView:

<ScrollView
    style={$style.category_container}
    horizontal={true}
    showsHorizontalScrollIndicator={false}
    automaticallyAdjustContentInsets={true}
>
    <Item title={'1'} />
    <Item title={'2'} />
</ScrollView>

Item is a component which loads several thumbnails. My application planned for both LTR and RTL users, so there is change in directions when it comes to RTL.

The problem is when I'm using RTL interface - the ScrollView still moving from left to right and I can't see all my thumbnails.

How can I solve it?

回答1:

If someone will run into this in the future: There isn't any 'built-in' property that will set ScrollView's direction to RTL at the moment.

However That's what worked for me:

  • set flexDirection: 'row-reverse' to ScrollView's style, which will order your items from right to left.

  • use onContentSizeChange to init list's scroll on the right side.

Here's an example:

scrollListToStart(contentWidth, contentHeight) {
    if (I18nManager.isRTL) {
        this.scrollView.scrollTo({x: contentWidth});
    }
}

render() {
    let containerStyle = I18nManager.isRTL ? styles.RTLContainer : styles.LTRContainer;

    return (
        <ScrollView
            ref={ref => this.scrollView = ref}
            onContentSizeChange={this.scrollListToStart.bind(this)}
            horizontal={true}
            style={[styles.buttonsContainer, containerStyle]}>
            {this.renderButtons()}
        </ScrollView>
    )
}


const styles = StyleSheet.create({

    RTLContainer: {
        flexDirection: 'row-reverse'
    },

    LTRContainer: {
        flexDirection: 'row'
    }
})


回答2:

you can use this way i did this and worked for me This solution has 2 rounds

1-first make this style for your scrollView : style={{scaleX:-1}}

2-second make this style for each of your childs in scrollView : style={{scaleX:-1}}

For Example

 <ScrollView
                            horizontal={true}
                            contentContainerStyle={{height: 65}}
                            style={{scaleX:-1}}
                            showsHorizontalScrollIndicator={false}>
                            {
                                data.sports.map((data,index) => {
                                    return(
                                        <View key={index}
                                            style={{width:150,height:55,backgroundColor:'yellow', marginHorizontal:4,scaleX:-1}}/>
                                    )
                                })
                            }
                        </ScrollView>

As you can see my scrollview has scaleX = -1 style Also all of my childs in scrollView has scaleX = -1 style

as scaleX is deprecated in views you can use transform:[{rotateY:'180deg'}] instead