首页 > 解决方案 > React Native - 如何设置 ScrollView 内的视图宽度以适应?

问题描述

我的水平 ScrollView 中有多个视图。如何设置它们,使每个视图都具有与 ScrollView 完全相同的尺寸?
我想使用分页并在滑动时转到 ScrollView 中的下一个视图。我尝试过使用width : "100%",但它不起作用,因为 ScrollView 没有固定尺寸,但这基本上就是我想要对其中的视图做的事情。这是我的代码:

export default class HorizontalScrollView extends Component {
    render () {
    screenWidth = "100%"
        return ( 
            <ScrollView 
            contentContainerStyle={styles.scrollable}
            horizontal={true}
            snapToInterval={screenWidth}
            decelerationRate={"fast"}
            >
                <View style={StyleSheet.compose(styles.insideContainer, {"width" : screenWidth, "backgroundColor" : "red"})}>
                    <Text>Screen 1</Text>
                </View>
                <View style={StyleSheet.compose(styles.insideContainer, {"width" : screenWidth, "backgroundColor" : "blue"})}>
                    <Text>Screen 3</Text>
                </View>
                <View style={StyleSheet.compose(styles.insideContainer, {"width" : screenWidth, "backgroundColor" : "green"})}>
                    <Text>Screen 2</Text>
                </View>
            </

样式表:

styles = StyleSheet.create({
    "scrollable" : {
        "backgroundColor" : "black",
        "height" : "100%"
    },
    "insideContainer" : {
        "alignItems" : "center",
        "justifyContent" : "center",
        "flex" : 1,
    }
})

PS - 我正在使用 Android Samsung Galaxy M30 进行测试。

任何帮助或解释将不胜感激。
谢谢你。

标签: javascriptandroidreactjsreact-native

解决方案


如果您的滚动视图是屏幕的宽度,您可以将每个视图内部的宽度设置为

Dimensions.get(“screen”).width

然后将 ScrollView 的 pagingEnabled 属性设置为 true,您应该有一个带有全宽子视图的分页滚动器。


推荐阅读