我希望能够创建一个子组件,它就像一个带有文本和相应导航动作的链接部分。我的主屏幕有以下内容。
const linkList = [{
title: "Some information",
onPress: () => {
this.navigation.navigate("WebViewScreen", {
title: "Some title",
uri: "https://SomeLink.com"
});
}},{
title: "Some information2",
onPress: () => {
this.navigation.navigate("WebViewScreen", {
title: "Some title2",
uri: "https://SomeLink2.com"
});
} }];
在渲染部分,我有
<GuideLinkSection links={linkList} />
我的构造函数是这样的。
constructor(props) {
super(props);
const { navigation } = this.props;
this.navigation = navigation;
}
在我的子组件中,我有:
renderGuideListSection = () => {
const { links, navigat } = this.props;
return links.map(link => {
return (
<TouchableOpacity style={styles.view} onPress={link.onPress}>
<Image style={styles.image} source={LinkImage} />
<Text style={styles.titleText}>{link.title}</Text>
</TouchableOpacity>
);
});
};
render() {
return this.renderGuideListSection();
}
这给了我一个错误:"Cannot read property 'navigation' of undefined. 有什么办法可以在不使用多个道具的情况下实现这个功能?
let linkList = [
{
title: 'Some information',
navigateTo: 'WebViewScreen',
label: 'Some title',
uri: 'https://SomeLink.com'
},
{
title: 'Some information2',
navigateTo: 'WebViewScreen2',
label: 'Some title2',
uri: 'https://SomeLink2.com'
}
];
你可以像上面一样存储数组。
下面是你的方法,将被调用 onPress
.
redirectTo = ({navigateTo, label, uri}) => {
let {navigation} = this.props;
navigation.navigate(navigateTo, {
title,
uri
})
}
renderGuideListSection = () => {
const { links } = this.props;
return links.map(link => {
return (
<TouchableOpacity style={styles.view} onPress={() => this.RedirectTo(link)}>
<Image style={styles.image} source={LinkImage} />
<Text style={styles.titleText}>{link.title}</Text>
</TouchableOpacity>
);
});