简体   繁体   English

如何使 ScrollView 组件的大小与 React Native 中的屏幕大小成比例?

[英]How Do I Make ScrollView Components Size a Ratio of Screen Size in React Native?

I'm working with React Native and I have a ScrollView with a small, finite number of Components (hence why I'm not using FlatList ).我正在使用 React Native 并且我有一个ScrollView其中包含少量有限的组件(因此我不使用FlatList )。

As best as I can tell, I need to provide a height to the components for them to be big enough to render in the ScrollView and hardcoding the height with just pixels seems to work.尽我所知,我需要为组件提供一个height ,使它们足够大以在ScrollView呈现,并且仅使用像素对height进行硬编码似乎可行。

Screenshot of the height as 250 pixels.高度为 250 像素的屏幕截图。

I've also just found that you can use a percentage for height/width .我还刚刚发现您可以使用百分比表示 height/width But when I try doing this for my components within my ScrollView , the components all become diminutive.但是当我尝试为我的ScrollView中的组件执行此操作时,这些组件都变得很小。

Screenshot of height as 25% not working.高度为 25% 的屏幕截图不起作用。

I get that the components might behave differently in a ScrollView as opposed to in a normal View , so I was wondering if we have to specify the exact number of pixels for each Component or if there's a better way to do this.我知道组件在ScrollView行为可能与在普通View ,所以我想知道我们是否必须为每个 Component 指定确切的像素数,或者是否有更好的方法来做到这一点。

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;

you better use Dimensions from React Native你最好使用 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
    },
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM