React Native/React 导航,同级组件 [英] React Native / React navigation, same level component
问题描述
我有 2 个类:用于主页的默认类 HomeScreen 和用于在 HomeScreen 上生成平面列表的另一个类 MyListem>.我的问题是我没有成功地在我的 MyList 类中构建我的导航功能.
I have 2 classes: my default class HomeScreen used for the home page and another class MyList which I use to generate a flatlist on my HomeScreen. My problem is that I do not succeed in building my navigation function in my MyList class.
我总是收到以下错误:找不到变量:导航".
I always get the following error: "Can't find variable: navigate".
我看了这个在顶级组件上调用导航,但我真的不知道如何在我的代码中实现它.
I took a look at this Calling Navigate on Top Level Component but I really don't know how to implement it in my code.
这是我尝试过的:
class MyList extends React.Component {
_keyExtractor = (item, index) => item.note.id;
_renderItem = ({ item }) => (
<TouchableNativeFeedback
onPress={() => navigate('Note', { noteId: item.note.id })} >
<View>
<Text style={styles.noteElementTitle} >{item.note.title}</Text>
<Text style={styles.noteElementBody} >{item.note.body}</Text>
</View>
</TouchableNativeFeedback>
);
render() {
return (
<FlatList
data={this.props.data}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
);
}
}
export default class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Notes',
headerStyle: { backgroundColor: 'rgb(255, 187, 0)' },
headerTitleStyle: { color: 'white' },
};
render() {
const { navigate } = this.props.navigation;
return (
<MyList
data={this.state.data}
load={this.state.load}
navig={this.props.navigation}
>
</MyList>
);
}
}
const Project = StackNavigator({
Home: { screen: HomeScreen },
NewNote: { screen: NewNoteScreen },
Note: { screen: NoteScreen }
});
AppRegistry.registerComponent('Project', () => Project);
感谢您的帮助.
推荐答案
因为 MyList
组件不是堆栈的一部分,所以导航道具不可用.
Because your MyList
component is not part of your stack the navigation prop is not available for that.
您有两个选择.
您可以手动将导航道具传递给 MyList 的第一个选项
First option you can pass the navigation prop manually to MyList
render() {
const { navigate } = this.props.navigation;
return (
<MyList
data={this.state.data}
load={this.state.load}
navigation={this.props.navigation}
>
</MyList>
);
}
第二个选项,您可以使用 withNavigation
.
Second option you can use withNavigation
.
withNavigation
是通过导航的高阶组件prop 到一个包裹的组件中.当您无法通过导航道具直接进入组件,或者不想传递它在嵌套很深的孩子的情况下.
withNavigation
is a Higher Order Component which passes the navigation prop into a wrapped Component. It's useful when you cannot pass the navigation prop into the component directly, or don't want to pass it in case of a deeply nested child.
import { Button } 'react-native';
import { withNavigation } from 'react-navigation';
const MyComponent = ({ to, navigation }) => (
<Button title={`navigate to ${to}`} onPress={() => navigation.navigate(to)} />
);
const MyComponentWithNavigation = withNavigation(MyComponent);
这篇关于React Native/React 导航,同级组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!