如何处理反应原生捕捉轮播中的Onpress事件

时间:2017-09-07 09:34:39

标签: javascript react-native

我有一个班级,在那个班级我正在展示像这样的轮播组件

sampleclass.js



.
.
. 
render{
return (
<Image ..> 
<Text>
text 
</Text>
<Image ..>
<js file tag where carousel is defined />
</Image>

<Text>
text 
</Text>
<Image ..>
<js file tag where carousel is defined />
</Image>
.
.
.
</Image>
);
}

function fname(params..){
I also need to access carousel ref here 
}
&#13;
&#13;
&#13;

我还有另一个课程,我已经定义了 carousel

carouselclass.js

&#13;
&#13;
import React, { PureComponent } from 'react';
import { Dimensions, StyleSheet, View } from 'react-native';

import Carousel from 'react-native-snap-carousel';

export default class ExampleCarousel extends PureComponent {
    state = {
        data: [{}, {}, {}, {}, {}, {}]
    }

    renderItem = () => (
        <View style={styles.tile} />
    );

    render () {
        return (
            <View style={styles.container}>
                <Carousel
                  data={this.state.data}
                  renderItem={this.renderItem}
                  itemWidth={Dimensions.get('window').width * 0.85}
                  sliderWidth={Dimensions.get('window').width}
                  containerCustomStyle={styles.carousel}
                  slideStyle={{ flex: 1 }}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        height: 300
    },
    carousel: {
        flex: 1,
        backgroundColor: 'red'
    },
    tile: {
        flex: 1,
        width: Dimensions.get('window').width * 0.85,
        backgroundColor: 'yellow'
    }
});
&#13;
&#13;
&#13;

我必须在sampleclass.js函数中处理轮播滑动组件的onPress事件

我怎么能这样做我知道怎么处理反应原生的onPress事件但是却无法用react-native-snap-carousel做这个,因为我第一次使用它时我已经阅读了文档中给出的例子但是找不到与此相关的事情

2 个答案:

答案 0 :(得分:1)

如果您想处理单个Carousel项onPress道具,则需要将其添加到渲染项目中。

示例

// change this
renderItem = () => (
    <View style={styles.tile} />
);

// to this
_onPressCarousel = () => {
    // here handle carousel press
}
renderItem = () => (
    <TouchableOpacity onPress={this._onPressCarousel} style={styles.tile}>
        <Image
            style={styles.button}
            source={require('./myButton.png')}
        />
    </TouchableOpacity>
);

答案 1 :(得分:0)

<Carousel
...
  renderItem={(carousel, parallaxProps) =>
    this._renderItem(carousel, parallaxProps)
}
...
/>


_renderItem(carousel, parallaxProps) {
  const { item } = carousel;
  return (
    <TouchableOpacity
      onPress={() => {
        this._handlePress(item._id);
      }}
    >
    ...