我现在正在使用 React Native 开发一个应用程序,我想从 FlatList 的每个项目进行导航。
例如,使用 create-react-native-app 。在App.js中,代码如下:
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
<FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
</View>
);
}
}
当我单击 FlatList 的一项时,我想导航到另一个组件,我的代码如下:
export default class App extends React.Component {
cb() {
this.props.navigator.push({
component: QuestionDetail
});
}
render() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
<FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text onPress={this.cb.bind(this)}>{item.key}</Text>}
/>
</View>
);
}
}
但是有一个错误。
任何人都可以如何从 FlatList 的项目中制作导航器吗?事实上,FlatList 的每个项目在单击时都应该创建一个导航器。
谢谢!
最佳答案
使用react-navigation(如果你想使用react-native-navigation,流程非常相似):
导入 StackNavigator:
imports...
import { Text, View, Button, FlatList, TouchableOpacity } from 'react-native';
import { StackNavigator } from 'react-navigation';
创建屏幕/容器堆栈:
class QuestionDetailScreen extends React.Component {
render() {
return (
<View>
<Text>QuestionDetail Screen</Text>
<Button
title="Go to List"
onPress={() => this.props.navigation.navigate('List')}
/>
</View>
);
}
}
在您的列表中:
class ListScreen extends React.Component {
cb = () => {
this.props.navigation.push('QuestionDetail');
}
render() {
return (
<View>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
<FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) =>
<TouchableOpacity onPress={() => this.cb()}>
<Text>{item.key}</Text>
</TouchableOpacity>}
/>
</View>
);
}
}
最后导出你的 stacknavigator:
const RootStack = StackNavigator(
{
List: {
screen: ListScreen,
},
QuestionDetail: {
screen: QuestionDetailScreen,
},
},
{
initialRouteName: 'List',
}
);
export default class App extends React.Component {
render() {
return <RootStack />;
}
}
关于javascript - 如何在 React Native 中从 FlatList 的一项进行导航?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48765789/