有没有一种方法可以让我在react native中发送一个对象数组,其中的对象包含文本和相应的onPRess动作的文本?

问题描述 投票:0回答:1

我希望能够创建一个子组件,它就像一个带有文本和相应导航动作的链接部分。我的主屏幕有以下内容。

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. 有什么办法可以在不使用多个道具的情况下实现这个功能?

reactjs react-native react-navigation
1个回答
1
投票
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>
  );
});
© www.soinside.com 2019 - 2024. All rights reserved.