gpt4 book ai didi

javascript - 如何在 React Native 中获取从子组件到父组件的回调

转载 作者:行者123 更新时间:2023-11-30 09:16:36 24 4
gpt4 key购买 nike

我一直在研究 react-native 以获得从 child 到 parent 的回调。下面是我的实现代码片段:

主视图.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 is undefined when tap on cell.

我已经关注了以下 https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17方法,但也没有成功任何建议都会有所帮助。

最佳答案

快速查看了您的代码。这是我发现的。

export default class ListCell extends PureComponent {
_onPress() {
this.props.onPressItem(this.props.item,this.props.index); //Change: passing prop onPressItem and calling _onPressItem
}
render() {
const item = this.props.item;
const price = item.price_formatted.split(' ')[0];
return (
<TouchableHighlight
style={styles.listCellContainer}
onPress={this._onPress} //Try: Also bind the event () => 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>
);

}
}

关于javascript - 如何在 React Native 中获取从子组件到父组件的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54707763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com