【问题标题】:How can I call StackNavigator from a class component in React Native?如何从 React Native 中的类组件调用 StackNavigator?
【发布时间】:2020-06-12 20:52:08
【问题描述】:

我正在尝试制作一个带有详细信息页面链接的 Hello World 页面。我了解如何使用 StackNavigator 使用功能组件进行导航。但我对它如何从类组件中工作感到困惑。我正在使用 React Navigation 5.x 和 React Native 0.61 如何将其转换为基于类的组件语法(因为大多数教程都遵循这一点,而不是新的功能组件)。

当我们使用功能组件时——从 React Native 0.61 开始——方法就是这样做:

function WelcomePage({ navigation }) {
      return (
        <View style={styles.container}>
          <Text style={styles.heading} >Welcome!</Text>
        </View>
      )
}

但是当我尝试在一个类中执行此操作时 - 我如何让它调用或从导航继承?

export default class HelloWorld extends Component<Props> {

  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Hello, world!</Text>
        <TouchableOpacity onPress={() => navigation.navigate('Details') }><Text>Go to Details</Text></TouchableOpacity>
      </View>
    );
  }
}

它给了我这个错误(见screenshot)。每当我尝试 this.something 时,我是否应该绑定“this”或其他东西,它会再次引发类似的错误。这是否与 React native 的新版本 0.61 和缺乏向后兼容性有关 - 或者它是什么?

【问题讨论】:

    标签: react-native react-router navigation react-native-android react-navigation-v5


    【解决方案1】:

    导航来自props

     //                       props
     function WelcomePage({ navigation }) { ... }
    

    要访问类组件中的道具,请执行this.props.navigation

    在您的示例中,它将是

    export default class HelloWorld extends Component<Props> {
    
      render() {
        return (
          <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
            <Text>Hello, world!</Text>
            {/*                                 getting navigation from props*/}
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Details') }><Text>Go to Details</Text></TouchableOpacity>
          </View>
        );
      }
    }
    

    请阅读docs关于道具的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多