this.props.navigation.navigate()不是对象

时间:2018-06-20 08:51:05

标签: react-native

为什么this.props.navigation.navigate()在我的组件中不可用?实际上,this.props是完全空的吗?我的设置是App.js将StartScreen.js和ListScreen.js添加到stackNavigator。然后将ListScreen.js用作Startscreen.js中的组件,并将用作堆栈导航...

ListScreen.js

import React, { Component } from "react";
import { ScrollView, View, Text, FlatList, ActivityIndicator } from "react-native";
import { List, ListItem } from 'react-native-elements';

import Styles from 'app/styles/Styles';
import Vars from 'app/vars/Vars';

class ListScreen extends Component {

    /*
    static navigationOptions = {
        title: 'Välkommen',
        headerStyle: Styles.header,
        headerTintColor: Vars.colors.primary,
        headerTitleStyle: Styles.headerTitle,
    };
*/
    constructor(props) {
        super(props);

        console.log(props);

        this.state = {
          loading: true,
          data: [],
          page: 1,
          seed: 1,
          error: null,
          refreshing: false
        };
    }

    componentDidMount() {

        this.fetchItems();
    }

    fetchItems = () => {
        const { page, seed } = this.state;
        const url = 'http://appadmin.test/api/menu/'+this.props.id;

        this.setState({ loading: true });

        fetch(url)
            .then(res => res.json())
            .then(res => {
                this.setState({
                    data: page === 1 ? res : [...this.state.data, ...res],
                    error: res.error || null,
                    loading: false,
                    refreshing: false
                });
            })
            .catch(error => {
                this.setState({ error, loading: false });
            });
    }

    handleRefresh = () => {

        console.log('several handleRefresh?');

        this.setState(
          {
            page: 1,
            seed: this.state.seed + 1,
            refreshing: true
          },
          () => {
            this.fetchItems();
          }
        );
    };

  handleLoadMore = () => {

      console.log('several handleLoadMore?');

    this.setState(
      {
        page: this.state.page + 1
      },
      () => {
        this.fetchItems();
      }
    );
  };


  renderFooter = () => {
    if (!this.state.loading) return null;

    return (
      <View
        style={{
          paddingVertical: 20,
        }}
      >
        <ActivityIndicator animating size="large" />
        <Text style={Styles.textCenter}>
            Laddar innehåll...
        </Text>
      </View>
    );
  };

  renderListItem = ({ item }) => (

      <ListItem
          title = {item.title}
          id = {item.id}
          automaticallyAdjustContentInsets={false}
          item = {item}
          leftIcon={{
              name: item.icon,
              style: Styles.listitemIcon,
              size: 36,
          }}
          onPress = {this.onItemPress}
          style = { Styles.listItem }
          titleStyle = { Styles.listitemTitle }
      />
  )

  onItemPress = (item) => {
    this.props.navigation.navigate('List', {
        id: item.id
    });
  }

    render() {



        return (
            <ScrollView contentContainerStyle={Styles.listContainer}>

                <FlatList
                    automaticallyAdjustContentInsets={false}
                    data = { this.state.data }
                    style={Styles.list}
                    keyExtractor={item => "key_"+item.id}
                    renderItem = { this.renderListItem }
                    ListFooterComponent={this.renderFooter}
                    onRefresh={this.handleRefresh}
                    refreshing={this.state.refreshing}
                    onEndReachedThreshold={50}
                />

            </ScrollView>
        );
    }
}
export default ListScreen;

StartScreen.js

import React, { Component } from "react";
import {
    View,
    ScrollView,
    Text,
    StyleSheet,
    Linking,
    FlatList
} from "react-native";

import Styles from 'app/styles/Styles';
import Vars from 'app/vars/Vars';

import ListScreen from 'app/screens/ListScreen';

import { List, ListItem } from 'react-native-elements';

import Menu from './../../assets/data/navigation.json';

class StartScreen extends Component {

    static navigationOptions = {
        title: 'Välkommen',
        headerStyle: Styles.header,
        headerTintColor: Vars.colors.primary,
        headerTitleStyle: Styles.headerTitle,
    };

    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            data: [],
            page: 1,
            seed: 1,
            error: null,
            refreshing: false,
        };
    }

    componentDidMount() {
        this.fetchList();
    }



    fetchList = () => {
        const { page, seed } = this.state;
        const url = 'http://appadmin.test/api/menu/root';

        this.setState({ loading: true });

        fetch(url)
            .then(response => {
                return response.json();
            })
            .then(json => {

                this.setState({
                    data: json,
                    error: null,
                    loading: false,
                    refreshing: false
                });
            })
            .catch(error => {
                this.setState({ error, loading: false });
            });
    }

    render() {
        return (

                <ScrollView style={Styles.scrollContainer}>
                    <View style={Styles.hero}>
                        <Text style={[Styles.h1, Styles.whiteText]}>
                            Region Halland
                        </Text>

                        <Text style={[Styles.lead, Styles.whiteText]}>
                            Välkommen
                        </Text>
                    </View>
                    <ListScreen id=""/>
                </ScrollView>
        );
    }
}
export default StartScreen;

App.js

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

import initCache from "app/utilities/initCache";

import { AppLoading } from 'expo';

import {
    createBottomTabNavigator,
    createStackNavigator
} from 'react-navigation'


import StartScreen from 'app/screens/StartScreen';
import ListScreen from 'app/screens/ListScreen';
import AboutScreen from 'app/screens/AboutScreen';
import { icon } from 'app/components/Image.js';

import Ionicons from 'react-native-vector-icons/Ionicons'




const StartStack = createStackNavigator({
  Start: {screen: StartScreen, tabBarLabel: 'Hem'},
  List: {screen: ListScreen},
}, {
    navigationOptions : {
        headerTitle:  <Image
           source={ icon }
           style={{ width: 30, height: 30 }} />,
        tabBarLabel: 'hem'
    }
});

const AboutStack = createStackNavigator({
  About: AboutScreen,
});



const Tabs = createBottomTabNavigator({
    StartStack: {screen: StartStack, navigationOptions: { title: 'Hem'}},
    AboutStack: {screen: AboutStack, navigationOptions: { title: 'Om Region Halland'}}
}, {
    navigationOptions: ({ navigation }) => ({
        tabBarIcon: ({ focused, tintColor }) => {
            const { routeName } = navigation.state;
            let iconName;

            if (routeName === 'AboutStack') {
                iconName = `ios-information-circle${focused ? '' : '-outline'}`;
            } else if (routeName === 'StartStack') {
                iconName = `ios-home${focused ? '' : '-outline'}`;
            }

            // You can return any component that you like here! We usually use an
            // icon component from react-native-vector-icons
            return <Ionicons name={iconName} size={24} color={tintColor} />;
      },
    }),
    tabBarOptions: {
      activeTintColor: '#0b457e',
      inactiveTintColor: 'gray',
    },
  })

export default class App extends React.Component {

    state = {
        appIsReady: false,
    };

    componentWillMount() {
        this._loadAssetsAsync();
    }

    async _loadAssetsAsync() {
        try {
            await initCache({
                fonts: [
                    {'scala-sans-regular': require('./assets/fonts/ScalaSans-Regular.ttf')},
                    {'scala-sans-bold': require('./assets/fonts/ScalaSans-Bold.ttf')},
                ]
            });
        } catch (e) {
            console.warn(
                'There was an error caching assets (see: main.js), perhaps due to a ' +
                'network timeout, so we skipped caching. Reload the app to try again.'
            );
            console.log(e.message);
        } finally {
            this.setState({ appIsReady: true });
        }
    }

    render() {
        if (this.state.appIsReady) {
          return (
            <Tabs />
          );
        } else {
          return <AppLoading />;
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

const {导航} = this.props.navigation; 然后将其用作:navigation('Signup')}