react-native - react native - 使用“prop-types”在组件中回调
问题描述
我有画廊组件,如:
import React from 'react';
... Some import
import PropTypes from 'prop-types';
import {
TouchableOpacity,
Image,
FlatList
} from 'react-native';
export default class Gallery extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: 0,
data: this.props.data
}
}
render() {
return (
<FlatList
showsHorizontalScrollIndicator={false}
horizontal={true}
data={this.state.data}
keyExtractor={(item, index) => item.id}
renderItem={({item, index}) =>
<TouchableOpacity
disabled={this.props.overlay && this.state.selected==index}
// onPress={this.props.actionOnPress}
onPress={()=>{
if(this.props.overlay) {
this.setState({
selected: index,
data: [...this.props.data]
});
}
this.props.actionOnPress;
}}>
<Image
source={{uri: item.imageUrl}}
style={[gallery.galleryItem, this.props.overlay && this.state.selected!=index ?gallery.overlay : null,
index==0 ? gallery.firstGalleryItem : ( index+1 == Object.keys(this.props.data).length ? gallery.lastGalleryItem : null )]}/>
</TouchableOpacity>
}
/>
);
}
}
Gallery.propTypes = {
data: PropTypes.array,
actionOnPress: PropTypes.func,
overlay: PropTypes.bool
}
我已经使用了 Gallery 组件,例如
import React from 'react';
import common from '../../assets/styles/common/common'
import galleryPreview from '../../assets/styles/common/galleryPreview'
import icons from '../../assets/styles/common/icon'
import Icons from '../../config/ConstantIcon'
import Gallery from '../common/Gallery'
import {
View,
Text,
StatusBar,
TouchableOpacity,
Image
} from 'react-native';
const data = [ List item here];
export default class GalleryPreview extends React.Component {
render() {
return (
<View>
... Some code here
<Gallery data={data} overlay={true}/>
... Some code here
</View>
);
}
}
如何使用来自 Gallery 组件的回调,例如<Gallery data={data} actionOnPress={({item, index})=> console.log(item)}/>
. item
并将index
从 Gallery 组件中获取。
我用过onPress={this.props.actionOnPress}
但不能插入
if(this.props.overlay) {
this.setState({
selected: index,
data: [...this.props.data]
});
}
而不是回调参数item
和index
你们能帮帮我吗?
谢谢,
解决方案
只需使用参数调用函数:
onPress={() => {
...
this.props.actionOnPress({ item, index });
}}