【问题标题】:How Do I Make ScrollView Components Size a Ratio of Screen Size in React Native?如何在 React Native 中使 ScrollView 组件大小与屏幕大小成比例?
【发布时间】:2021-01-20 22:04:07
【问题描述】:

我正在使用 React Native 并且我有一个 ScrollView,其中包含少量有限数量的组件(因此我不使用 FlatList)。

据我所知,我需要为组件提供 height 以使它们足够大以在 ScrollView 中呈现,并且仅使用像素硬编码 height 似乎可行。

Screenshot of the height as 250 pixels.

我也刚刚发现you can use a percentage for height/width。但是当我尝试为我的ScrollView 中的组件执行此操作时,组件都变小了。

Screenshot of height as 25% not working.

我知道组件在 ScrollView 中的行为可能与普通 View 中的不同,所以我想知道我们是否必须为每个组件指定确切的像素数,或者是否有更好的方法来这样做。

import React, {Component} from 'react';
import {SafeAreaView, ScrollView, StyleSheet, View} from 'react-native';

const styles = StyleSheet.create({
    item: {
        height: 250,
        // height: '25%' <--- Doesn't work
        margin: 2,
        borderRadius: 15
    },
})

const Item = ({color}) => (
    <View style={[styles.item,
        {backgroundColor: color}]}/>
  );

class App extends Component {

    render = () => {
        return (
            <SafeAreaView style={{flex: 1}}>
                <ScrollView  style={{flex: 1}}>
                    <Item color={'chocolate'} />
                    <Item color={'darkseagreen'} />
                    <Item color={'khaki'} />
                    <Item color={'palegreen'} />
                    <Item color={'paleturquoise'} />
                    <Item color={'aqua'} />
                </ScrollView>
            </SafeAreaView>
        )
    }
}

export default App;

【问题讨论】:

    标签: javascript android reactjs react-native mobile


    【解决方案1】:

    你最好使用来自 React Native 的 Dimensions

    import {SafeAreaView, ScrollView, StyleSheet, View, Dimensions} from 'react-native';
    
    
    const styles = StyleSheet.create({
        item: {
            height: Dimensions.get('window').height * 0.25,
            margin: 2,
            borderRadius: 15
        },
    })
    

    【讨论】:

    • 工作就像一个魅力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2020-12-29
    • 2021-07-23
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多