react-native - ScrollView React Native Horizontal 不工作
问题描述
我正在开发应用程序RN 0.59.8
。我正在尝试使用ScrollView
. 这是我的代码的基础(对不起,我无法分享更多细节):
import React, { Component, Fragment } from 'react';
import {
ScrollView,
} from 'react-native';
import {
Container,
Content,
} from 'native-base';
import { Grid, Row } from 'react-native-easy-grid';
import ChildComponent from './ChildComponent';
class MyComponent extends Component {
render() {
const {
data,
} = this.props;
return (
<Container>
<Content>
<Grid>
<Row>
<ScrollView
horizontal
contentContainerStyle={{
flex: 1, flexGrow: 1, flexDirection: 'row',
}}
>
{
data.map((item, index) => {
const order = index;
return (
<Fragment key={order}>
{
<ChildComponent />
}
</Fragment>
);
})
}
</ScrollView>
</Row>
</Grid>
</Content>
</Container>
);
}
}
export default MyComponent;
当前行为:
- 如果
contentContainerStyle={{ flex: 1, flexGrow: 1, flexDirection: 'row' }}
,第二个数据不出现 - 如果
contentContainerStyle={{ flex: 1, flexGrow: 1, flexDirection: 'column' }}
,第二个数据垂直出现 - 如果
contentContainerStyle={{ flexDirection: 'row' }}
,则第二个数据不出现且内容比屏幕宽度宽
我的反对意见是:
- 我想让它水平滚动
- 每个数据将适合屏幕宽度
任何帮助都会非常有帮助。谢谢!!!
解决方案
直接来自 React Native 文档,滚动视图的子视图水平排列成一行而不是垂直排列成一列,你需要使用它的唯一道具是horizontal
.
<ScrollView horizontal>
<Child/>
</ScrollView>
我创建了一个小吃给你看,@abranhe/stackoverflow-56721203:
要使其适合屏幕宽度,请使用您的组件并:
import { Dimensions } from 'react-native';
Dimensions.get('width').width
演示源代码:
import React, { Component } from 'react';
import { Text, View, StyleSheet, Image, ScrollView } from 'react-native';
import data from './data';
export default class App extends Component {
renderCity(city) {
return (
<View style={styles.cardContainer}>
<View style={styles.card}>
<Image source={{ uri: city.img }} style={styles.image} />
<Text style={styles.title}>{city.title}</Text>
</View>
</View>
);
}
render() {
return (
<View style={styles.container}>
<ScrollView horizontal>
{data.map(city => {
return this.renderCity(city);
})}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ecf0f1',
marginTop: 30,
},
title: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
image: {
width: 200,
height: 200,
borderRadius: 10,
marginTop: 10,
},
cardContainer: {
justifyContent: 'center',
},
card: {
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
margin: 20,
borderRadius: 10,
width: 220,
},
});
记住
一些基于原生的UI 组件具有绝对值,您可以更改主题变量,以使其适合您的需求。
如果您不想显示滚动指示器,可以设置为false
ScrollView的showsHorizontalScrollIndicator
道具。
推荐阅读
- css - 将滚动文本的 css 翻译同步到相同的速度(但持续时间不同)
- c - 链表中的整数值有时被设置为 0
- python - tkinter 的 radioButton 似乎丢失了 state="disabled" 的配置
- android - Android:错误:不能从静态上下文引用非静态类型变量 T
- c - 程序中计算C中单词、句子和字母数量的问题
- xsl-fo - 仅在其列中换行的文本 XSL fo
- python - 用泡菜保存变量
- android - 使用 JFrog Artifactory 的 Kotlin 多平台库
- .net - 从完整的框架项目中引用 .NET 5.0 程序集?
- java - 使用 volley 解析 JSON 中的 android Recyclerview 适配器问题