如何向React Navigation导航器中的组件传递props?
嘿,这个问题我之前也碰到过,给你几个实用的解决办法,根据你的场景选就行:
方法1:直接封装Tab组件(最简单直接)
你可以在定义Tab导航的screen时,用箭头函数把目标组件包裹起来,直接传递你需要的props,子组件就能直接拿到这些参数啦:
// Search.js const Navigator = createMaterialTopTabNavigator({ Wines: () => <Wines searchKeyword={this.state.keyword} userInfo={this.props.user} />, Stores: () => <Stores searchKeyword={this.state.keyword} />, Vineyards: () => <Vineyards searchKeyword={this.state.keyword} />, Restaurants: () => <Restaurants searchKeyword={this.state.keyword} /> }); // 然后在Wines组件里直接用props接收 const Wines = ({ searchKeyword, userInfo }) => { console.log('拿到的搜索关键词:', searchKeyword); return (/* 组件内容 */); }
方法2:使用initialParams(传递初始参数)
如果是给Tab组件传递初始参数,你可以在定义screen的时候配置initialParams(React Navigation 5+版本支持),子组件通过route.params获取:
// Search.js const Navigator = createMaterialTopTabNavigator({ Wines: { screen: Wines, initialParams: { searchKeyword: this.state.keyword } }, // 其他Tab同理 }); // Wines组件中获取参数 const Wines = ({ route }) => { const { searchKeyword } = route.params; return (/* 组件内容 */); }
方法3:React Context(适合多组件共享数据)
如果需要传递的参数比较多,或者多个Tab组件都需要共享同一批数据,用React Context会更灵活:
// 先创建一个Context import React, { createContext, useContext } from 'react'; const SearchContext = createContext(); // Search组件中提供Context值 const Navigator = createMaterialTopTabNavigator({ Wines, Stores, Vineyards, Restaurants }); // 在render方法里 render() { return ( <SearchContext.Provider value={{ searchKeyword: this.state.keyword, user: this.props.user }}> <Navigator /> </SearchContext.Provider> ); } // Wines组件中消费Context const Wines = () => { const { searchKeyword, user } = useContext(SearchContext); return (/* 组件内容 */); }
补充:旧版React Navigation(4及以下)的screenProps
如果你用的是React Navigation 4或更早的版本,可以直接给Navigator组件传递screenProps,子组件通过props.screenProps获取:
// 在render方法中 <Navigator screenProps={{ searchKeyword: this.state.keyword }} /> // Wines组件中 const Wines = ({ screenProps }) => { console.log(screenProps.searchKeyword); return (/* 组件内容 */); }
选哪种方法看你的实际需求啦,简单传参用方法1就够,复杂场景用Context更合适~
内容的提问来源于stack exchange,提问作者James Ko
相关产品推荐
相关产品推荐

