gpt4 book ai didi

reactjs - 如何在 StackNavigator 中传递 Prop

转载 作者:行者123 更新时间:2023-12-04 01:56:55 25 4
gpt4 key购买 nike

const MainNavigator = StackNavigator({
Home: {
screen: Tabs
},

Collection_Products : {
screen : Collection_Products,
navigationOptions : ({ navigation }) => ({

title : `${navigation.state.params.name.toUpperCase()}`
}),
},

MainProduct : {
screen : (props) => <MainProduct {...props} />,
},

});


export default class MainNav extends React.Component {
constructor() {
super();
this.state = {
checkout: { lineItems: { edges: [] } }
};

}

method1 = (args) => {

}
render() {

return (
<View style={{flex: 1}}>
<MainNavigator checkout= {this.state.checkout} method1 = {this.method1}/>
</View>
);
}
}

我正在使用 React Native 来构建应用程序。我想将方法​​ 1 传递给不同的子组件。如何在 MainProduct 组件中传递 method1 函数?使用我使用的语法,我只能将导航器 Prop 传递给子组件。

最佳答案

React Navigation v5 和 v6 已接受的答案已过时

screenProps 不再可用,这导致了几个问题。

改用 React context

引用自 react-navigation 5.x,

由于 React Navigation 5.x 的基于组件的 API,我们有一个比 screenProps 更好的替代品,它没有这些缺点:React Context。使用 React Context,可以以高性能和类型安全的方式将数据传递给任何子组件,我们不需要学习新的 API!

或者,你可以使用 routeProps

将参数传递给路由。 v6 doc

navigation.navigate('RouteName', {/* params go here */})

如果您不熟悉context

这里是您可以如何使用上下文来传递 props。

例子:

  import React from 'react'

// Create context outside of your component
// which can be export to your child component
const MyContext = React.createContext()

export default function MyParentComponent() {
const myContext = {
whatIWhatMyChildToKnow: 'Hi, I am your father.',
}
return (
<MyContext.Provider value={myContext}>
// Dont pass your own props to your navigator
// other than RNavigation props
<YourStackNavigator>
...stack logic
</YourStackNavigator>
</MyContext.Provider>
)
}

// access your context value here
function MyChildScreen() {
const { whatIWhatMyChildToKnow } = React.useContext(MyContext)
// will display 'Hi, I am your father.'
return <span>{whatIWantMyChildToKnow}</span>
}

关于reactjs - 如何在 StackNavigator 中传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49951208/

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