【问题标题】:Using class instead of stateless functional component - react native使用类而不是无状态功能组件 - 反应原生
【发布时间】:2017-05-28 09:13:32
【问题描述】:

我是原生反应的新手。我使用了功能组件而不是可以正常工作的类。在这里我不能使用构造函数、状态、生命周期方法等。所以我想创建一个类而不是函数,但没有运气。

功能组件(index.android.js)

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Button,
  View
} from 'react-native';

import {
  TabNavigator
} from 'react-navigation';

import MyHomeScreen from './MyHomeScreen';
import MyNotificationsScreen from './MyNotificationsScreen';

const TabNavigation = TabNavigator({
  Home: {
    screen: MyHomeScreen,
  },
  Notifications: {
    screen: MyNotificationsScreen,
  },
}, {
  tabBarOptions: {
    activeTintColor: '#e91e63',
  },
});

AppRegistry.registerComponent('TabNavigation', () => TabNavigation);

MyHomeScreen.js

export default class MyHomeScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Home',
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('./chats-icon.png')}
      />
    ),
  };

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    );
  }
}

MyNotificationsScreen.js

export default class MyNotificationsScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Notifications',
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('./notif-icon.png')}
      />
    ),
  };

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.goBack()}
        title="Go back home"
      />
    );
  }
}

使用类:我想使用类如下。如何使它像上面名为 TabNavigation 的功能组件一样工作?

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Button,
  View
} from 'react-native';

import {
  TabNavigator
} from 'react-navigation';

import MyHomeScreen from './MyHomeScreen';
import MyNotificationsScreen from './MyNotificationsScreen';    

export default class TabNavigation extends Component {

  render() {
    return (
      <View>
      //what to do here
      </View>
    );
  }
}   

【问题讨论】:

    标签: react-native react-navigation react-tabs


    【解决方案1】:

    如果您想在顶层呈现 TabNavigation,那么方法与您的第一个示例一样。 TabNavigator() 构造一个组件。

    您的问题似乎并不清楚您的用例,但如果您想要一个顶级类,您可以将 TabNavigation 包装在一个类中:

    // ...
    render() {
      return (
        <TabNavigation />
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-21
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      相关资源
      最近更新 更多