首页 > 解决方案 > 如何使用 props 从父组件获取状态

问题描述

我是 React Native 的新手,我真的不明白如何使用道具。我有 2 个组件是父组件和子组件。那么我怎样才能在父母中获得状态?

我尝试在这里阅读很多答案并阅读了很多文件,但对我来说道具非常困难。

import React from 'react';
import { View, Text, Button } from 'react-native';
import {
  createAppContainer,
  createStackNavigator,
  StackActions,
  NavigationActions,
} from 'react-navigation';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      name: 'Hello',
    };
  }
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Parent Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {this.props.navigation('Child')}}/>
      </View>
    );
  }
}

class Child extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Child Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {console.log(this.props)}}/>     <--- show data of parent 
      </View>
    );
  }
}

const AppNavigator = createStackNavigator(
  {
    Parent: {
      screen: Parent,
    },
    Child: {
      screen: Child,
    },
  },
  {
    initialRouteName: 'Parent',
  }
);

export default createAppContainer(AppNavigator);

我希望当我像这样控制台记录表单数据时

>{parent: Parent}
  >parent: Parent
  >context: {}
  >props: {screenProps: undefined, navigation: {…}}
  >state: {  name: 'Hello'}
...

标签: react-native

解决方案


您需要从父级传递这些数据

onPress={() => {this.props.navigation('Child',{parentData:'Pass Data From Here'})}}

并在孩子中获取这些数据

const { navigation } = this.props;
const itemId = navigation.getParam('parentData', 'Default Value');

推荐阅读