官术网_书友最值得收藏!

The ScrollView component

So far, we know about three components: View , Text, and StyleSheet. Now, imagine a case where we have a lot of rows to show in the application—something such as table of information pops into my mind. Obviously, it will be a long table, but the screen is small, so we will make it scrollable—up and down, like in a browser. This may seem trivial as a concept, but this isn't very easy to implement, which is why React Native provides the ScrollView component.

Let's see this problem in action. Check out Example 3_ No ScrollView problem from the Chapter 2 folder to get started.

Here, we have a typical TaskList component, which converts every task into a Task component. Task displays its name and description as Text. It's a very simple mechanism, but once a number of tasks is huge, such as 20 or more tasks, it fills the entire screen, and suddenly you realize that you cannot scroll like in a browser window:

// Chapter 2 / Example 3 / src / TaskList.js
export const TaskList = ({tasks, containerStyles}) => (
<View style={containerStyles}>
{tasks.map(task => // problems if task list is huge
<ExpandableTask
key={task.name + task.description}
name={task.name}
description={task.description}
/>
)}
</View>
);

To fix this issue and make the content scrollable, replace View with ScrollView. You also need to rename the style prop to contentContainerStyle. Please see the full example, as follows:

// Chapter 2 / Example 4 / src / TaskList.js
import React from 'react';
import Task from './Task';
import PropTypes from 'prop-types';
import {StyleSheet, Text, ScrollView, View} from 'react-native';
import makeExpandable from './makeExpandable';

const ExpandableTask = makeExpandable(Task);

export const TaskList = ({tasks, containerStyles}) => (
<ScrollView contentContainerStyle={containerStyles}>
{tasks.map(task =>
<ExpandableTask
key={task.name + task.description}
name={task.name}
description={task.description}
/>
)}
</ScrollView>
);

const styles = StyleSheet.create({
container: {
backgroundColor: '#fff'
}
});

TaskList.propTypes = {
tasks: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
description: PropTypes.string.isRequired
})),
containerStyles: PropTypes.oneOfType([
PropTypes.object,
PropTypes.number
])
};

TaskList.defaultProps = {
tasks: [],
containerStyles: styles.container
};

export default TaskList;

I have also included PropTypes definitions so that you can practice what we have learned in the previous section.

Notice the use of the key prop ( key={task.name + task.description}) on the Task component. This is required when you render collections so that React can distinguish elements on prop changes and, if possible, avoid unnecessary repainting of the component.
主站蜘蛛池模板: 大港区| 仲巴县| 邢台县| 贡觉县| 嫩江县| 阿图什市| 略阳县| 霍邱县| 高雄市| 鹿邑县| 翼城县| 濮阳市| 万源市| 拜城县| 海盐县| 呼玛县| 栾川县| 安陆市| 安仁县| 赤水市| 宽甸| 达拉特旗| 康平县| 安福县| 巴中市| 灵武市| 都昌县| 五常市| 闽侯县| 安图县| 庆云县| 蒙阴县| 海宁市| 锡林郭勒盟| 汕头市| 新干县| 五寨县| 泸水县| 无棣县| 永清县| 靖西县|