我有以下代码:
import React, { Component } from 'react';
import {TabNavigator} from 'react-navigation';
import {Button,FlatList,Text,View} from 'react-native';
class Recent extends Component<{}> {
getData() {
return ["Locked in room","Fell on the floor", "Need help with Stairs"];
}
render() {
let {navigate} = this.props.navigation;
console.log(this.props.user); // this line gives me undefined
return (
<FlatList
style={{flex:1,width:"100%"}}
data={this.getData()}
keyExtractor={(item, index) => index}
renderItem={({item}) => <Text onPress={()=>navigate("NextPage",{user:this.props.user})}>{item}</Text>}
/>
);
}
}
const RequestRouter = TabNavigator({
Recent1: {screen: Recent},
Recent2:{screen:Recent}
}
);
export default class App extends Component<{}> {
render() {
let {navigate} = this.props.navigation;
const user = this.props.navigation.state.params.user;
return (
<View style={{flex:1,flexDirection:"column"}}>
<Button onPress={()=>navigate("NextPage",{user:user})}
title="Go"
accessibilityLabel="Go"
/>
<View style={{width:"100%",flex:6,flexDirection:"column"}}>
<RequestRouter user={user} />
</View>
</View>
);
}
}
我遇到的问题是console.log(this.props.user);
内的class Recent extends Component
给了我一个undefined
。这是因为我不知道如何将user
中的App.render()
变量正确传递到Recent.render()
,因为有TabNavigator
将请求路由到Recent
1}} class。
如何将user
变量从App.render()
传递到Recent
?
答案 0 :(得分:1)
您可以使用screenProps将道具传递给TabNavigator
内的子组件,如下所示:
<RequestRouter screenProps={user} />
您可以通过this.props.screenProps.user