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

[英]this.props.navigation.navigate() is not an object


Why is this.props.navigation.navigate() not available in my component? In fact, this.props is completely empty? My setup is that App.js adds StartScreen.js and ListScreen.js to a stackNavigator. ListScreen.js is then used as a component in Startscreen.js and will serve as a stacknavigation...

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

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 个解决方案

#1


-1  

const { navigate } = this.props.navigation; then use it as : navigate(‘Signup’)}

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


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/06/20/31920de0d8a3d3b7fb3be56ad2f65788.html



 
  © 2014-2022 ITdaan.com 联系我们: