我有函数式组件,我在 onPress
处传递参数。代码如下:
PAGE1
const onPress = (data) => {
navigation.goBack();
route.params.onPress(data);
};
我能够将它传递给一个功能组件,在那里我获取数据,并且能够更新我在功能组件中的状态。以下是功能组件的代码片段:
PAGE2
function gotoSearch() {
navigation.navigate('SearchScreen',{
onPress:(data)=>{
console.log("Location Selected",data);
updateStateVar({
...stateVar,
address_line_1: data.address_line1,
address_line_2: data.address_line2,
area: data.area,
city: data.city,
country: data.country,
pincode: data.postCode,
lat:data.lat,
lng:data.lng,
});
}
});
}
我有另一个组件,它是一个类组件,我尝试做同样的事情,但显示了错误。以下是类组件的代码片段:
PAGE3
gotoSearch = () => {
this.props.navigation.navigate('SearchScreen'), {
onPress: (data) => {
console.log("Location Selected",data);
}
}
}
错误:
cannot read property of 'onPress' of undefined
const onPress = (data) => {
navigation.goBack();
route.params.onPress(data);
^
};
答案 0 :(得分:0)
您需要导出 onPress 函数
export const onPress = (data) => {
navigation.goBack();
route.params.onPress(data);
};
然后在你的类组件中使用它
gotoSearch = () => {
this.props.navigation.navigate('SearchScreen'), {
onPress: (data) => {
console.log("Location Selected",data);
}
}
如果你的函数存在于不同的文件中,然后先导入它再使用
import {onPress} from './file.js'