React Native 如何让 ScrollView 组件的大小与屏幕大小成比例?
How Do I Make ScrollView Components Size a Ratio of Screen Size in React Native?
我正在使用 React Native,我有一个 ScrollView
,其中的组件数量有限(因此我不使用 FlatList
)。
据我所知,我需要为组件提供一个 height
以使它们足够大以在 ScrollView
中呈现并硬编码 height
像素似乎有效。
Screenshot of the height as 250 pixels.
我也刚发现 。但是当我尝试为我的 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;
你最好使用来自 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
},
})
我正在使用 React Native,我有一个 ScrollView
,其中的组件数量有限(因此我不使用 FlatList
)。
据我所知,我需要为组件提供一个 height
以使它们足够大以在 ScrollView
中呈现并硬编码 height
像素似乎有效。
Screenshot of the height as 250 pixels.
我也刚发现 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;
你最好使用来自 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
},
})