我正在使用本机FlatList创建数据列表,在RootStack导航器中,将FlatList组件作为主屏幕,而Details组件作为DetailsScreen。我希望详细信息屏幕显示动态数据,无论清单列表项的ID和文本如何显示在详细信息屏幕中。我知道如何转到新屏幕,但无法弄清楚如何将List组件状态数据作为props传递给Details组件。
我也收到错误消息“失败的子上下文类型”。
我希望我清楚。我试图解决这个问题已经三个小时了。如果您能帮助我解决这个问题,对您来说太好了。
import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
class List extends Component {
state = {
rows: [
{ id: 0, text: 'View' },
{ id: 1, text: 'Text' },
{ id: 2, text: 'Image' },
{ id: 3, text: 'ScrollView' },
{ id: 4, text: 'ListView' }
]
};
renderItem = ({ item }) => {
return (
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate(
'Details',
{
/*how to pass data here*/
}
)}
>
<Text style={styles.row}>{item.text}</Text>
</TouchableOpacity>
);
};
render() {
const extractKey = ({ id }) => id;
return (
<FlatList
style={styles.container}
data={this.state.rows}
renderItem={this.renderItem}
keyExtractor={extractKey}
/>
);
}
}
class DetailsScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>The id is {this.props.id} /*how to get data here*/</Text>
<Text>you are in {this.props.text} /*how to get data here*/</Text>
</View>
);
}
}
const RootStack = createStackNavigator({
List: List,
Details: DetailsScreen
});
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
const styles = StyleSheet.create({
container: {
marginTop: 20,
flex: 1
},
row: {
padding: 15,
marginBottom: 5,
backgroundColor: 'skyblue'
}
});
通过将此代码粘贴到Expo中,您可以立即获得结果
答案 0 :(得分:0)
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate(
'Details',
{
/*how to pass data here*/
Name:'Jhon Lennon',
Age: 58
Male: true
}
)}
>
在详细信息屏幕中
class DetailsScreen extends React.Component {
componentDidMount() {
this.getInfo();
}
getInfo(){
//you can do it this way or access it directly
//var Name =this.props.navigation.getParam('Name ', 'No Name'); //second parameter is a callback
//var Age=this.props.navigation.getParam('Age', 20);
//var Male=this.props.navigation.getParam('Male', false);
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>The Name is {this.props.navigation.state.params.Name||'NoName'} /*NoName is also a callback*/</Text>
<Text>you are {this.props.navigation.state.params.Age||'0'} years old /*0 is the callback*/</Text>
</View>
);
}
}
更多信息here
此外,您应该避免将根导航器包装在组件内
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
应该只是
export default createAppContainer(RootStack);