react-native-swiper下一个/上一个按钮事件

时间:2019-08-01 07:08:41

标签: react-native swiper

滑动索引值按页面顺序显示。 但是,当按下按钮时,索引值会升至无穷大。

ex)“下一步”按钮-> 6 / 5、7 / 5、8 / 5

我想做的是在5/5处停止按钮事件,但我不知道该怎么办。

https://github.com/leecade/react-native-swiper

App.js

const renderPagination = (index, total, context) => {

  return (
    <View style={styles.paginationStyle}>
      <Text style={{ color: 'grey' }}>
        <Text style={styles.paginationText}>{index + 1}</Text>/{total}
      </Text>
    </View>
  )
}

export default class App extends Component {

  constructor(props){
    super(props);
    this.onPressNext = this.onPressNext.bind(this);
    this.state = {
      idxActive: 1
    }
 }

  onPressPrev = () => {
    this.refs.swiper.scrollBy(-1)
  }

  onPressNext = () => {
    this.refs.swiper.scrollBy(1);
  }

  render() {
    return (

      <View style={styles.container}>


        <Swiper
          style={styles.wrapper}
          renderPagination={renderPagination}
          showsButtons={false}
          loop={false}
          ref={'swiper'}
        >
          <View style={styles.slide}>
            <Text style={styles.text}>1 page</Text>
          </View>
          <View style={styles.slide}>
            <Text style={styles.text}>2 page</Text>
          </View>
          <View style={styles.slide}>
            <Text style={styles.text}>3 page</Text>
          </View>
          <View style={styles.slide}>
            <Text style={styles.text}>4 page</Text>
          </View>
          <View style={styles.slide}>
            <Text style={styles.text}>5 page</Text>
          </View>
        </Swiper>

        <View style={styles.buttoncontainer}>
          <Button
            onPress={this.onPressPrev}
            title="previous">
          </Button>
          <Button
            onPress={this.onPressNext}
            title="next">
          </Button>

        </View>
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

使用滑动器的onIndexedChanged道具获取最新的index并将其保存在本地组件状态。像这样:

export default class App extends Component {

  constructor(props){
    super(props);
    this.onPressNext = this.onPressNext.bind(this);
    this.onPressPrev = this.onPressPrev.bind(this);
    this.state = {
      idxActive: 0
    }
 }

  onPressPrev = () => {
    const {idxActive} = this.state;
    if (idxActive > 0) {
      this.refs.swiper.scrollBy(-1)
    }
  }

  onPressNext = () => {
    const {idxActive} = this.state;
    // Probably best set as a constant somewhere vs a hardcoded 5
    if (idxActive < 5) {
      this.refs.swiper.scrollBy(1);
    }
  }

  render() {
    return (

      <View style={styles.container}>


        <Swiper
          ... etc.
          onIndexChanged={idxActive => this.setState({idxActive})}
        >
          ... etc.