13

我正在学习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;

4

2 回答 2

14

syntax has nothing to do with React Native it is called Destructuring assignment in es6 / es2015

const { navigate } = this.props.navigation;

is equivilent to with exception to var and const .

var navigate = this.props.navigation.navigate

the example without Destructuring should look like this

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>
    );
  }
}
于 2017-03-28T05:11:30.120 回答
1

在您的 ServiceAction 中包含this.props.navigation如下内容:

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

因为props.navigation默认情况下在您的父组件上

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

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

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

于 2019-04-03T16:50:53.557 回答