引入 react-native-pager-view 组件
javascript
import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, PagerView, Button } from '@tarojs/components'
import PagerView from 'react-native-pager-view';
export default class MyComponent extends Taro.Component {
constructor(props) {
super(props)
this.pagerViewRef = React.createRef()
this.state = {
currentPage: 0,
}
}
goToPage = (pageNumber) => {
if (this.pagerViewRef.current) {
this.pagerViewRef.current.setPage(pageNumber)
this.setState({ currentPage: pageNumber })
}
}
render() {
return (
<View>
<PagerView
ref={this.pagerViewRef}
initialPage={0}
style={{ height: 200 }}
onPageSelected={(e) => this.setState({ tabIndex: e.nativeEvent.position })}
>
<View style={{ backgroundColor: 'red', flex: 1 }}>第一页</View>
<View style={{ backgroundColor: 'blue', flex: 1 }}>第二页</View>
<View style={{ backgroundColor: 'green', flex: 1 }}>第三页</View>
</PagerView>
<Button onClick={() => this.goToPage(1)}>Go to Page 1</Button>
</View>
)
}
}
react native
javascript
import * as React from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import PagerView from 'react-native-pager-view';
const Tabs = () => {
const [page, setPage] = React.useState(0);
return (
<View style={styles.container}>
<View style={styles.tabBar}>
<TouchableOpacity onPress={() => setPage(0)}>
<Text>Tab 1</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setPage(1)}>
<Text>Tab 2</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setPage(2)}>
<Text>Tab 3</Text>
</TouchableOpacity>
</View>
<PagerView style={styles.pagerView} initialPage={page} onPageSelected={e => setPage(e.nativeEvent.position)}>
<View key="1">