简体   繁体   English

在 React Native JSX 中渲染 2D 数组中的项目

[英]Render items from 2D Array in React Native JSX

I'd like to create a menu based on a 2 dimensional Array: title and icon name.我想创建一个基于二维数组的菜单:标题和图标名称。
Here's what I tried:这是我尝试过的:

class Menu2 extends React.Component{
  constructor(props) {
   super(props);
   this.state = { Items: [['Home','home'],['User','user'],['Messages','envelope'], ['Finances','wallet'], ['Meal','silverware-fork-knife']]}
 }

 render(){
   <View style={styles.menu}>
   {this.state.Items.map((Items,i) => {
     return(
       <TouchableOpacity style={[styles.menu_item,styles.menu_item]} onPress={() => {this.props.navigation.navigate(Items[i][0]);}}>
       <FontAwesome name={Items[i][1]} size={40} color="#fff"/>
         <Text style={styles.menu_text}>{Items[i][0]}</Text>
       </TouchableOpacity>
     )
   })};
    </View>
 }
}

export default Menu2

Error returned is "TypeError undefined is not an object (evaluating 'Items[i][1]')"返回的错误是“未定义的类型错误不是对象(正在评估 'Items[i][1]')”

What I was expecting is that "i" would by the iteration 0, 1, 2, 3, 4 (looping 5 times in my case) of my array and so Items[i][0] = the title and Items[i][1] = the icon name.我期待的是“i”会通过我的数组的迭代 0、1、2、3、4(在我的情况下循环 5 次),因此 Items[i][0] = 标题和 Items[i] [1] = 图标名称。 But I couldn't make it work like I would have liked.但我不能让它像我希望的那样工作。

Any ideas?有任何想法吗?

You're using .map incorrectly!您使用的.map不正确!

The MDN documentation for Array.prototype.map() shows how to use the callback for this Array.prototype.map()MDN 文档展示了如何为此使用回调

function callback(currentValue, index, array)

Your callback this.state.Items.map((Items,i) => puts the currentValue into a variable named Items , but then you use Items as if it were the full array!您的回调this.state.Items.map((Items,i) =>currentValue放入名为Items的变量中,但随后您将Items用作完整数组!

Solution解决方案

Try this instead:试试这个:

   {this.state.Items.map((currentItem) => {
     return(
       <TouchableOpacity style={[styles.menu_item,styles.menu_item]} onPress={() => {this.props.navigation.navigate(currentItem[0]);}}>
       <FontAwesome name={currentItem[1]} size={40} color="#fff"/>
         <Text style={styles.menu_text}>{currentItem[0]}</Text>
       </TouchableOpacity>
     )
   })};

It should be Items[0]它应该是 Items[0]

      <FontAwesome name={Items[1]} size={40} color="#fff"/>
         <Text style={styles.menu_text}>{Items[0]}</Text>
       </TouchableOpacity>

check this working codesandbox https://codesandbox.io/s/proud-cache-gyuge检查此工作代码和框https://codesandbox.io/s/proud-cache-gyuge

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM