简体   繁体   English

将数字添加到列表项 React-native

[英]Add numbers to list item React-native

I have a list of ingredients which I would like to add numbering to like....我有一个成分列表,我想添加编号来喜欢....

Step 1... 1 ½ cups shredded Swiss cheese Step 2... 4 teaspoons all-purpose flour Step 3... ½ cup cooked ham, diced Step 4... 3 eggs第 1 步... 1 ½ 杯瑞士奶酪丝 第 2 步... 4 茶匙通用面粉 第 3 步... ½ 杯切碎的熟火腿 第 4 步... 3 个鸡蛋

to differentiate each ingredient with Step numbering.用步骤编号区分每种成分。 I'm trying to make an algorithm to do this automatically.我正在尝试制作一种算法来自动执行此操作。 I've currently tried to map through each ingredient but I keep getting an error.我目前已尝试通过每种成分进行 map,但我一直收到错误消息。 I'm new to React Native and have a basic knowledge on Javascript this is probably easy but I just can't wrap my head around the way to do this.我是 React Native 的新手,并且对 Javascript 有基本的了解,这可能很容易,但我就是不知道该怎么做。

This is my code这是我的代码

ingredients = [
    "1 ½ cups shredded Swiss cheese",
    '4 teaspoons all-purpose flour',
    '½ cup cooked ham, diced',
    '3 eggs',
    '1 cup milk'
]

const Ingridients = () => (
<View style={[styles.scene, { backgroundColor: 'white', height:'30%' }]}>
    {ingredients.map(ingri => <Text style={styles.ingredients} key={ingri}>{ingri.length}{ingri}</Text>)}
</View>);

I would really appreciate it from the bottom of my heart if someone could help me out to add numbering to this list.如果有人可以帮助我将编号添加到此列表中,我将衷心感谢。 Thank you in advance!!!!!先感谢您!!!!!

You can get the current iteration's index with the second parameter that Array.map function provides您可以使用Array.map function 提供的第二个参数获取当前迭代的索引

{ingredients.map((ingredient, index) => (
    <Text style={styles.ingredients} key={index}>
        {index + 1}: {ingredient}
    </Text>
))}

You can use the index of each element, Since javascript arrays are 0-indexed you can do something like this:您可以使用每个元素的索引,因为 javascript arrays 是 0 索引,您可以执行以下操作:

const Ingridients = () => (
<View style={[styles.scene, { backgroundColor: 'white', height:'30%' }]}>
    {ingredients.map( (ingri, index) =>  // <- introducing the index argument
<Text style={styles.ingredients} key={ingri}>
{'Step ' + (index+1) } // <- use the index + 1 since it starts with 0
{ingri.length}{ingri}
</Text>)}
</View>);

The Array map function provides current iteration index as second argument.数组map function 提供current iteration index作为第二个参数。

const Ingridients = () => (
<View style={[styles.scene, { backgroundColor: 'white', height:'30%' }]}>
    {ingredients.map((ingri, index) => <Text style={styles.ingredients} key={ingri}>Step {index + 1}. {ingri}</Text>)}
</View>);

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

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