【问题标题】:React Native Navigation const { navigate } = this.props.navigation;React Native Navigation const { navigate } = this.props.navigation;
【发布时间】:2017-03-28 05:06:37
【问题描述】:

我正在学习 react-native 导航 https://reactnavigation.org/docs/intro/ 。我在示例中看到了

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Text>Hello, Chat App!</Text>
        <Button
          onPress={() => navigate('Chat')}
          title="Chat with Lucy"
        />
      </View>
    );
  }
}

我无法理解const { navigate } = this.props.navigation; 的这行代码到底是什么

【问题讨论】:

  • 这叫做解构赋值。和const navigate = this.props.navigation.navigate一样。
  • @AndrewLi 非常感谢!

标签: react-native react-navigation


【解决方案1】:

语法与 React Native 无关 在 es6 / es2015 中称为 Destructuring assignment

const { navigate } = this.props.navigation;

等价于 var 和 const 除外。

var navigate = this.props.navigation.navigate

没有解构的例子应该是这样的

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    return (
      <View>
        <Text>Hello, Chat App!</Text>
        <Button
          onPress={() => this.props.navigation.navigate('Chat')}
          title="Chat with Lucy"
        />
      </View>
    );
  }
}

【讨论】:

  • 我的程序在哪里以及如何使用它?它是如何工作的?
  • 它基本上是直接从this.props.navigate拉取navigate方法并将其分配给变量navigate
  • 所以这里是onPress={() =&gt; navigate('Chat')} 是不是引用const { navigate } = this.props.navigation;
  • 是的:即onPress={ () =&gt; this.props.navigation.navigate('Chat') }完全相同的东西。
  • this.props.navigation 我从中了解到的是navigation 是道具。我有一个问题,它是哪个组件的属性?
【解决方案2】:

在您的 ServiceAction 中包含 this.props.navigation 类似这样的内容:

<HomeScreen navigation={this.props.navigation}/>

因为props.navigation 默认在你的父组件上

在 HomeScreen 组件上,您将访问如下导航:

..
goToSignUp() {
   this.props.navigation.navigate('SignUp');
}
..

对我来说之前也很困惑。干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2021-04-05
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 2017-10-11
    相关资源
    最近更新 更多