javascript 在 TabNavigator 中反应导航传递道具

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46264767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:33:26  来源:igfitidea点击:

React Navigation pass props in TabNavigator

javascriptandroidreact-nativereact-navigation

提问by GhostPengy

I have props what are loaded from the server on the initial screen. I want to pass them to the rest of the tab screens. However, I have not found any examples online. I know of the screenProps, but have no idea how to set it up. All methods I have tried, have resulted in errors.

我在初始屏幕上有从服务器加载的道具。我想将它们传递给其余的选项卡屏幕。但是,我没有在网上找到任何示例。我知道 screenProps,但不知道如何设置它。我尝试过的所有方法都导致错误。

const EProj = TabNavigator({
  Home: { screen: HomeScreen },
  Map: { screen: MapG },
  Login: { screen: Login },
  Profile: { screen: Profile },
}, {
  tabBarPosition: 'bottom',
  animationEnabled: true,
  tabBarOptions: {
    activeTintColor: '#1abc9c',
  },
});

This is my screen setup. Where should I place the screenProps?

这是我的屏幕设置。我应该把 screenProps 放在哪里?

<EProj
  screenProps={cats}
/>

Any good examples how to set this up would be helpful. Thanks in advance.

任何如何设置它的好例子都会有所帮助。提前致谢。

HomeScreen setup:

主屏幕设置:

class HomeScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Home',
  };

...

  componentWillMount(){
    console.log("Starting to load assets from server!");
    this.onLoadCats(); /*starts asset loading*/
  }

  render() {
    return (
      <View style={styles.container}>

        <Text>Welcome to alpha 1.17 This is hard system test.</Text>
        <AssetsLoad catsL={this.state.catsL} />
      </View>
    );
  }
}

回答by bennygenel

What you can do is create a higher order component that can return the navigation, and in that component's componentDidMount, you can load the data and pass it through screenProps.

您可以做的是创建一个可以返回导航的高阶组件,在该组件的 中componentDidMount,您可以加载数据并通过screenProps.

Example

例子

const EProj = TabNavigator({
  Home: { screen: HomeScreen },
  Map: { screen: MapG },
  Login: { screen: Login },
  Profile: { screen: Profile },
}, {
  tabBarPosition: 'bottom',
  animationEnabled: true,
  tabBarOptions: {
    activeTintColor: '#1abc9c',
  },
});

class MainNavigation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {cats: []};
  }
  componentDidMount() {
    this.onLoadCats().then((cats) => this.setState({ cats: cats }));
  }
  render() {
    return(<EProj screenProps={{ cats: this.state.cats}} />
  }
}

// Now you can do in your screens
console.log(this.props.screenProps.cats);

/* This is next line is wrong, please check update above */ 
/* console.log(this.props.navigation.state.params.cats); */