javascript - 如何在反应导航中将函数/方法作为参数传递。导航
问题描述
我有两个名为 Home.js 和 ViewList.js 的组件,用户可以使用堆栈导航器导航到每个组件。
我想将 updatePrice 函数作为参数从 Home.js 传递到 ViewList.js 下面是我试图完成的片段。以下是该应用程序如何工作的简要说明。用户从 Home.js 组件导航到 ViewList.js 组件。在 View.js 组件中,用户可以输入商品的价格。
onChangeText 我想运行 updatePrice 函数,以便更新 Home.js 组件中列表项的状态。我的问题是我似乎无法弄清楚如何将 updatePrice 函数传递给 ViewList 。关于我如何做到这一点的任何建议?
下面是 Home.js 的代码片段
export default function Home({navigation}){
const updatePrice = (key, id, price) =>{
setShoppingList(list =>
list.map(list =>
list.key === key
? {
...list,
listItems: list.listItems.map(item =>
item.id === id
? {
...item,
price
}
:item
)
}
: list
)
)
console.log(shoppingLists);
}
return(
<View style={globalStyles.container}>
<FlatList
data={shoppingLists}
renderItem={({ item }) =>(
<TouchableOpacity onPress={() =>
// Here I try to pass the function through the
//navigate prop as an object.
navigation.navigate('ViewList',item,{'updatePrice': () => this.updatePrice})}>
{/*Create card container to wrap text in*/}
<Card>
<Text>{item.name}</Text>
<Text>Budget: $ {item.budget}</Text>
</Card>
</TouchableOpacity>
)}
keyExtractor={item => item.key}
/>
</View>
)
}
这是另一个 ViewList.js
export default function ViewList({navigation}){
const shoppingListKey = navigation.getParam('key');
const updatePrice = navigation.getParam('updatePrice');
const listInfo = navigation.getParam('listItems');
return(
<View style={globalStyles.container}>
<Card>
<Text>{navigation.getParam('name')}</Text>
<Text>Budget: $ {budget}</Text>
<Text> Total: {total}</Text>
<FlatList
data={listInfo}
renderItem={({item}) =>(
<View>
<Text>{item.name}</Text>
<Text>Price: {item.price}</Text>
<TextInput
style={globalStyles.globalTextInput}
keyboardType={'numeric'}
onChangeText={(value) =>
//Here I try to retrieve the updatePrice function but I got an error.
this.props.navigation.state.params.updatePrice(shoppingListKey,item.id,value)}
/>
</View>
)}
keyExtractor={item => item.id}
/>
</Card>
</View>
)
}
解决方案
推荐阅读
- laravel - 在 Google 联系人模板中的 Vuetify v-list 中定义路由器链接
- python - 如何添加带有标签的轴以供将来参考?
- ios - 如何在 Swift 5 中使用数组响应为 API 创建视图模型
- c# - 是否可以从 Web 服务器获取请求数据到控制台应用程序?
- webrtc - 如何在pubnub webrtc lib中获得没有cam的广播连接?
- c - 关于 fputs() 的困惑
- c# - FileStreamResult 对象被释放
- javascript - 如何在 ng-if 中使用动态范围变量
- excel - 循环浏览 Outlook 文件夹中的电子邮件项目以将每个表复制到 Excel
- javascript - ChartJS 悬停工具提示颜色未显示正确颜色