如何在StackNavigator中传递Props?附相关实现代码
嘿,我来给你详细拆解在StackNavigator里传递Props的几种实用方法,结合你提供的代码片段来唠明白~
1. 直接给单个Screen组件注入Props(对应你代码里的MainProduct)
先看你代码里这段写法:
MainProduct : { screen : (props) => <MainProduct {...props} />, },
这里的思路是把StackNavigator自动传递的props(比如navigation、route这些核心对象)直接展开传给你的自定义组件。如果要加自己的专属Props,直接在JSX里追加就行:
// 比如把MainNav里的state和方法传进去 MainProduct : { screen : (props) => <MainProduct {...props} checkout={this.state.checkout} handleMethod={this.method1} />, },
⚠️ 注意:如果要传递外层组件(比如你的MainNav)的state或方法,得确保MainNavigator的定义能访问到这个上下文——比如把Navigator的定义移到MainNav的render方法里,或者用下面的全局传递方式。
2. 通过跳转参数传递动态数据(对应你代码里的Collection_Products)
你在Collection_Products的navigationOptions里用到了navigation.state.params.name,这就是通过跳转时传参的方式:
// 在其他页面触发跳转时,带上参数 navigation.navigate('Collection_Products', { name: '数码配件' })
这种方式适合传递页面跳转时的动态数据,比如页面标题、商品ID之类的。不仅能在navigationOptions里用,在Collection_Products组件内部也能通过this.props.navigation.state.params拿到这些参数。
3. 给整个Navigator传递全局通用Props
如果想让StackNavigator里的所有Screen都能拿到同一个Props(比如全局状态、通用方法),可以在渲染Navigator的时候直接传screenProps:
render() { return ( <MainNavigator screenProps={{ globalCheckout: this.state.checkout, commonMethod: this.method1 }} /> ) }
之后在任意Screen组件里,就能通过this.props.screenProps获取这些全局数据:
// 在Tabs或者Collection_Products组件内使用 console.log(this.props.screenProps.globalCheckout)
4. 复杂场景用React Context(进阶玩法)
如果你的项目层级多、跨组件传参需求复杂,用Context会更省心。先在MainNav里创建一个Context:
const AppContext = React.createContext() export default class MainNav extends React.Component { constructor() { super(); this.state = { checkout: { lineItems: { edges: [] } } }; } method1 = (args) => { /* 你的方法逻辑 */ } render() { return ( <AppContext.Provider value={{ checkout: this.state.checkout, method1: this.method1 }}> <MainNavigator /> </AppContext.Provider> ) } }
然后在任意Screen组件里,用useContext(函数组件)或者Context.Consumer(类组件)获取数据:
// 函数组件示例 import { useContext } from 'react' import { AppContext } from './MainNav' function Collection_Products() { const { checkout, method1 } = useContext(AppContext) // 直接用这些数据就行 return <div>{checkout.lineItems.edges.length}</div> }
简单总结下:跳转时的动态数据用navigation.navigate带参数;单个组件的自定义Props用Screen的函数写法;全局通用数据用screenProps;复杂跨层级传参用React Context。
内容的提问来源于stack exchange,提问作者hitarth

