簡體   English   中英

將數字添加到列表項 React-native

[英]Add numbers to list item React-native

我有一個成分列表,我想添加編號來喜歡....

第 1 步... 1 ½ 杯瑞士奶酪絲 第 2 步... 4 茶匙通用面粉 第 3 步... ½ 杯切碎的熟火腿 第 4 步... 3 個雞蛋

用步驟編號區分每種成分。 我正在嘗試制作一種算法來自動執行此操作。 我目前已嘗試通過每種成分進行 map,但我一直收到錯誤消息。 我是 React Native 的新手,並且對 Javascript 有基本的了解,這可能很容易,但我就是不知道該怎么做。

這是我的代碼

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>);

如果有人可以幫助我將編號添加到此列表中,我將衷心感謝。 先感謝您!!!!!

您可以使用Array.map function 提供的第二個參數獲取當前迭代的索引

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

您可以使用每個元素的索引,因為 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>);

數組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