react-native-snap-carousel:如何在项目点击时调用函数
react-native-snap-corousel: How to call a function on item click
我想在点击旋转木马中的项目时调用一个函数。下面是我的代码。
onPress(){
console.log("onPress");
}
_renderItem({item, index}) {
return (
<TouchableWithoutFeedback
onPress={this.onPress.bind(this)}>
<View style={styles.slide}>
<Image
source={{ uri: item.row.image_name }}
style={styles.image}
/>
</View>
</TouchableWithoutFeedback>
);
}
当我点击该项目时,我收到错误提示 _this6.onPress is not a function
。
我可以像下面这样直接点击提醒。
<TouchableWithoutFeedback onPress={()=>{ Alert.alert("onPress");}}>
如何在项目点击时调用方法?
您的所有函数都需要绑定到 this
的上下文中。这意味着你也需要做 this._renderItem.bind(this)
。
示例 (为简单起见删除了一些部分)
export default class ImageCarousel extends Component {
constructor(props) {
super(props);
this.state = {
slider1ActiveSlide: SLIDER_1_FIRST_ITEM,
};
this._renderItem = this._renderItem.bind(this);
this.onPress = this.onPress.bind(this);
}
onPress() {
Alert.alert('Hi');
}
_renderItem({ item, index }) {
return (
<TouchableOpacity onPress={this.onPress}>
<Image style={styles.image} source={{ uri: item.illustration }} />
</TouchableOpacity>
);
}
mainExample(number, title) {
const { slider1ActiveSlide } = this.state;
return (
<View>
<Carousel
ref={c => (this._slider1Ref = c)}
data={ENTRIES1}
renderItem={this._renderItem}
{/* ... */}
/>
{/* ... */}
</View>
);
}
render() {
const example1 = this.mainExample(
1,
'Default layout | Loop | Autoplay | Scale | Opacity | Pagination with tappable dots'
);
return <ScrollView>{example1}</ScrollView>;
}
}
我想在点击旋转木马中的项目时调用一个函数。下面是我的代码。
onPress(){
console.log("onPress");
}
_renderItem({item, index}) {
return (
<TouchableWithoutFeedback
onPress={this.onPress.bind(this)}>
<View style={styles.slide}>
<Image
source={{ uri: item.row.image_name }}
style={styles.image}
/>
</View>
</TouchableWithoutFeedback>
);
}
当我点击该项目时,我收到错误提示 _this6.onPress is not a function
。
我可以像下面这样直接点击提醒。
<TouchableWithoutFeedback onPress={()=>{ Alert.alert("onPress");}}>
如何在项目点击时调用方法?
您的所有函数都需要绑定到 this
的上下文中。这意味着你也需要做 this._renderItem.bind(this)
。
示例 (为简单起见删除了一些部分)
export default class ImageCarousel extends Component {
constructor(props) {
super(props);
this.state = {
slider1ActiveSlide: SLIDER_1_FIRST_ITEM,
};
this._renderItem = this._renderItem.bind(this);
this.onPress = this.onPress.bind(this);
}
onPress() {
Alert.alert('Hi');
}
_renderItem({ item, index }) {
return (
<TouchableOpacity onPress={this.onPress}>
<Image style={styles.image} source={{ uri: item.illustration }} />
</TouchableOpacity>
);
}
mainExample(number, title) {
const { slider1ActiveSlide } = this.state;
return (
<View>
<Carousel
ref={c => (this._slider1Ref = c)}
data={ENTRIES1}
renderItem={this._renderItem}
{/* ... */}
/>
{/* ... */}
</View>
);
}
render() {
const example1 = this.mainExample(
1,
'Default layout | Loop | Autoplay | Scale | Opacity | Pagination with tappable dots'
);
return <ScrollView>{example1}</ScrollView>;
}
}