[英]How to change page in ViewPager react-native
I'm using ViewPager in my app with react-native-step-indicator but I need to change the page upon using specific button.我在我的应用程序中使用 ViewPager 和 react-native-step-indicator 但我需要在使用特定按钮时更改页面。
Here is part of my code:这是我的代码的一部分:
import ViewPager from 'react-native-viewpager';
import StepIndicator from 'react-native-step-indicator';
const PAGES = ['Business','Logo','Description'];
export default class UserSetup extends Component {
constructor() {
super();
var dataSource = new ViewPager.DataSource({
pageHasChanged: (p1, p2) => p1 !== p2,
});
this.state = {
dataSource: dataSource.cloneWithPages(PAGES),
currentPage:0,
token: null,
userId: null,
name: "",
address1: "",
address2: "",
city: "",
country: "",
zipcode: "",
url: "",
phone: "",
description: "",
}
}
render() {
const { navigate } = this.props.navigation;
return (...
<View style={styles.stepIndicator}>
<StepIndicator customStyles={indicatorStyles}
currentPosition={this.state.currentPage}
stepCount={3}
labels={['Basic info','Logo','Description']} />
</View>
<ViewPager dataSource={this.state.dataSource}
renderPage={this.renderViewPagerPage}
onChangePage={(page) => {this.setState({currentPage:page})}}
/>
</View>
);
}
Then in the first page I have a button and I need to change first page to second page when button is pressed.然后在第一页我有一个按钮,按下按钮时我需要将第一页更改为第二页。 How can I do that?
我怎样才能做到这一点?
Use reference使用参考
ref={(viewPager) => {this.viewPager = viewPager}}
later you can integrate it with event listener稍后您可以将其与事件侦听器集成
onPress={()=>this.viewPager.setPage(index)}
Adding on to @LorisTujiba's answer.添加到@LorisTujiba 的答案。 This code worked for me when I was trying to change the page on click of the button.
当我尝试通过单击按钮更改页面时,此代码对我有用。
1. Declaration part for ref<\/strong> 1. ref的声明部分<\/strong>
const ref = React.useRef(PagerView); const ref = React.useRef(PagerView);
<\/blockquote>
2. Passing the ref<\/strong> 2. 传递参考<\/strong>
< PagerView initialPage={0} ref={ref}> <PagerView 初始页={0} ref={ref}>
<\/blockquote>
3. Change page on button click<\/strong> 3.点击按钮改变页面<\/strong>
ref.current.setPage(currentIndex + 1); ref.current.setPage(currentIndex + 1);
<\/blockquote>"
I found the solution, just need to include this in the ViewPager Options:我找到了解决方案,只需要在 ViewPager 选项中包含它:
ref={(viewpager) => {this.viewpager = viewpager}}
And then setting in the button OnPress on the page like this:然后在页面上的按钮 OnPress 中设置,如下所示:
this.viewpager.goToPage(NumberPage);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.