ScrollView 是一個可以容納多個元件和視圖的滾動容器。它是 React Native 中的核心元件之一,使用它可以實現垂直和水平滾動。
ScrollView 會根據運行平台對應到對應的原生元件。所以在 Android 上,視圖會對應到 在這個範例中,ScrollView 包含一個 View 和一個 Text 元件,並且它們被包裹在一個 View 中。 要使用ScrollView,首先需要匯入該元件− 要在ScrollView中顯示的資料儲存在狀態物件的names中,如下所示− The data i.e this.state.names is an array. The map() method is used on the array and the name is displayed inside View->Text Component as shown below − ScrollView works best for static data which is of small size.But if you want to work around with dynamic that can be a huge list best to make use of the FlatList component. Here is## the full code for ScrollView. 預設情況下,ScrollView垂直顯示數據。若要水平顯示數據,請使用以下屬性 horizontal={true} 如下所示− 以上是ScrollView元件是什麼,如何在React Native中使用它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!範例 1:使用 ScrollView 進行垂直捲動
import { Text, View, StyleSheet, ScrollView} from 'react-native';
state = {
names: [
{'name': 'Ben', 'id': 1},
{'name': 'Susan', 'id': 2},
{'name': 'Robert', 'id': 3},
{'name': 'Mary', 'id': 4},
{'name': 'Daniel', 'id': 5},
{'name': 'Laura', 'id': 6},
{'name': 'John', 'id': 7},
{'name': 'Debra', 'id': 8},
{'name': 'Aron', 'id': 9},
{'name': 'Ann', 'id': 10},
{'name': 'Steve', 'id': 11},
{'name': 'Olivia', 'id': 12}
]
}
<ScrollView>
{this.state.names.map((item, index) => (<View key = {item.id} style = {styles.item}><Text>{item.name}</Text></View>))
}
</ScrollView>
import React, { Component } from "react";
import { Text, View, StyleSheet, ScrollView} from 'react-native';
class ScrollViewExample extends Component {
state = {
names: [
{'name': 'Ben', 'id': 1},
{'name': 'Susan', 'id': 2},
{'name': 'Robert', 'id': 3},
{'name': 'Mary', 'id': 4},
{'name': 'Daniel', 'id': 5},
{'name': 'Laura', 'id': 6},
{'name': 'John', 'id': 7},
{'name': 'Debra', 'id': 8},
{'name': 'Aron', 'id': 9},
{'name': 'Ann', 'id': 10},
{'name': 'Steve', 'id': 11},
{'name': 'Olivia', 'id': 12}
]
}
render(props) {
return (
輸出
#範例2:使用ScrollView水平滾動
<ScrollView horizontal={true}>
{this.state.names.map((item, index) => (<View key = {item.id} style = {styles.item}><Text>{item.name}</Text></View>))
}
</ScrollView>
import React, { Component } from "react";
import { Text, View, StyleSheet, ScrollView} from 'react-native';
class ScrollViewExample extends Component {
state = {
names: [
{'name': 'Ben', 'id': 1},
{'name': 'Susan', 'id': 2},
{'name': 'Robert', 'id': 3},
{'name': 'Mary', 'id': 4},
{'name': 'Daniel', 'id': 5},
{'name': 'Laura', 'id': 6},
{'name': 'John', 'id': 7},
{'name': 'Debra', 'id': 8},
{'name': 'Aron', 'id': 9},
{'name': 'Ann', 'id': 10},
{'name': 'Steve', 'id': 11},
{'name': 'Olivia', 'id': 12}
]
}
render(props) {
return (
輸出
################################################################################################# #######