我一直在研究 react-native 以获取从孩子到父母的回调。下面是我的实现的代码片段:
MainView.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
Image,
TouchableHighlight,
FlatList,
Dimensions,
} from 'react-native';
import ListCell from './ListCell';
import {displayAlert} from './CustomAlert';
type Props = {
};
let winSize = Dimensions.get('window');
export default class MainView extends Component<Props> {
_keyExtractor = (item, index) => { return(index.toString());};
_renderItem = ({item, index}) => {
return (<ListCell
item={item}
index={index}
onPressItem={this._onPressItem}
/>);
};
_onPressItem = (item,index) => {
console.log("Pressed row : "+index);
displayAlert();
// this.props.navigation.navigate('Detail',{item: item});
};
render() {
return(
<FlatList
style={styles.flatListStyle}
data={this.props.listing}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
);
}
}
FlatList 的列表单元组件是:
ListCell.js
import React, {PureComponent} from 'react';
import {
StyleSheet,
TouchableHighlight,
View,
Image,
Text,
} from 'react-native'
export default class ListCell extends PureComponent {
_onPress() {
this.props._onPressItem(this.props.item,this.props.index);
}
render() {
const item = this.props.item;
const price = item.price_formatted.split(' ')[0];
return (
<TouchableHighlight
style={styles.listCellContainer}
onPress={this._onPress}
underlayColor='#dddddd'>
<View >
<View style={styles.rowContainer}>
<Image style={styles.thumb} source={{uri:item.img_url}}/>
<View style={styles.textContainer}>
<Text style={styles.price}>{price}</Text>
<Text style={styles.title}>{item.title}</Text>
</View>
</View>
</View>
</TouchableHighlight>
);
}
}
此代码在单个文件中声明时可以正常工作,但是当在两个不同的文件中分隔时,它会在点击单元格时给出错误说明 this.props._onPressItem
未定义。
我遵循了以下https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17方法,但没有成功任何建议都会有所帮助。