react-native - 如何使用 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'}
...
解决方案
您需要从父级传递这些数据
onPress={() => {this.props.navigation('Child',{parentData:'Pass Data From Here'})}}
并在孩子中获取这些数据
const { navigation } = this.props;
const itemId = navigation.getParam('parentData', 'Default Value');
推荐阅读
- javascript - 打字稿错误 - 类型和参数的参数隐式具有“任何”类型
- swift - AVPlayer 即使使用了toleranceBefore,Seek也不准确:kCMTimeZero
- java - Tomcat 在 CentO 上不起作用 - ExecStop=/bin/kill -15 $MAINPID (code=exited, status=1/FAILURE)
- firebase - 如何使用 if & else 条件(Firebase、SDK)获取子值
- android - 无法从 android 媒体记录器播放 mp4 视频
- php - 如何在一个查询中加入国家和城市?
- java - 泛型类 - 当我创建一个新对象时会发生什么?
- wordpress - 如何在联系表单 7 wordpress 中添加模式输入
- c# - 如何在应用程序代码中使用跟踪源?
- hadoop - 如何确定执行 hive 查询所需的作业总数