【问题标题】:How To Creating A Component That Works With StackNavigator?如何创建与 StackNavigator 一起使用的组件?
【发布时间】:2017-04-28 08:24:24
【问题描述】:

我正在尝试创建一个包含在“屏幕”文件中的全局导航栏。我对 React Native 很陌生,我遇到的问题是我也在尝试在包含的导航栏中使用 StackNavigator。通过这样做,我收到以下错误。

我正在使用以下代码。

import NavBar from "../../components/navBar";


export default class HomeView extends Component {
  static navigationOptions = {
    title: 'Home Screen',
    headerVisible: false,
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.contentWrapper}>
        <StatusBar hidden={true} />
        <NavBar />
        <View style={styles.boxTop}><Text>Test</Text></View>
        <View style={styles.boxBottom}><Text>Test</Text></View>
      </View>
    );
  }
}

在导航文件中。

import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native'


export default class NavBar extends Component {
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.contentWrapper}>
      </View>
    );
  }
}


var styles = StyleSheet.create({
  contentWrapper: {
    flex: 1,
    backgroundColor: "blue",
    height: 40,
  },
});

我不确定这是否是创建组件并包含 StackNavigator 的正确方法。

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    你刚刚得到它! navigation 属性仅适用于直接传递给 StackNavigator(或其他导航器)的屏幕。您可以通过两种方式从导航栏组件访问navigation

    第一种方法是在您使用时将导航道具传递给您的导航栏组件,就像这样。

    import NavBar from "../../components/navBar";
    
    
    export default class HomeView extends Component {
      static navigationOptions = {
        title: 'Home Screen',
        headerVisible: false,
      };
      render() {
        const { navigate } = this.props.navigation;
        return (
          <View style={styles.contentWrapper}>
            <StatusBar hidden={true} />
            <NavBar navigation={this.props.navigation} />
            <View style={styles.boxTop}><Text>Test</Text></View>
            <View style={styles.boxBottom}><Text>Test</Text></View>
          </View>
        );
      }
    }
    

    或者您可以使用高阶组件withNavigation 来包装您的导航栏并访问导航,但您无需记住每次使用导航栏组件时都将其作为道具传递。看起来像这样。

    import React, { Component } from 'react'
    import {
      StyleSheet,
      Text,
      View,
      Image
    } from 'react-native'
    import { withNavigation } from 'react-navigation';
    
    class NavBar extends Component {
      render() {
        const { navigate } = this.props.navigation;
        return (
          <View style={styles.contentWrapper}>
          </View>
        );
      }
    }
    
    var styles = StyleSheet.create({
      contentWrapper: {
        flex: 1,
        backgroundColor: "blue",
        height: 40,
      },
    });
    
    export default withNavigation(Navbar);
    

    【讨论】:

    • 感谢您的帮助,我现在就试试。
    猜你喜欢
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 2012-12-09
    相关资源
    最近更新 更多