首页 > 解决方案 > 基于循环渲染对象?

问题描述

我想根据列表中的条目 currentSelection呈现x对象的数量。x我试图这样做,但我得到一个错误,说它由于某种原因找不到item。如果我能得到一些帮助,我将不胜感激!

相关代码:

                  currentSelection.map(item => {
                    <View key={item.value} style={{position: 'absolute', right: 10, bottom: -15}}>
                        <MaterialCommunityIcons name="star" color="red" size={20}/>
                    </View>
                  });

用这个编辑语法错误:

                 currentSelection.map(item => {
                    return (
                        <View key={item.value} style={{position: 'absolute', right: 10, bottom: -15}}>
                            <MaterialCommunityIcons name="star" color="red" size={20}/>
                        </View>
                    ); //tried with ); and ) and got the same error
                  });

更多相关代码:

const renderItems = () => {
  currentSelection.map(item => {
    return (
      <View key={item.value} style={{position: 'absolute', right: 10, bottom: -15}}>
        <MaterialCommunityIcons name="star" color="red" size={20}/>
      </View>
    );
  });
}
return (
        <ScrollView>
            <View style={ [styles.iconPosition, {flexDirection:"row"}] }>
                <TouchableOpacity style={ styles.button } onPress={ () => navigation.dispatch(StackActions.pop(1))}>
                    <MaterialCommunityIcons name="arrow-left" color="red" size={30}/>
                </TouchableOpacity>
                <Image source = { Logo } style = { styles.iconSize } />
            </View>
            <View style={styles.tabBar}>
                <MaterialTabs
                    items={['Your Favorite Meals', 'Select Favorite Meals']}
                    selectedIndex={selectedTab}
                    onChange={setSelectedTab}
                    barColor="#ffffff"
                    indicatorColor="#000000"
                    activeTextColor="#000000"
                    inactiveTextColor="#908c8c"
                />
            </View>
            {selectedTab === 0 ? (
                <View>
                    <View style={ styles.selectMultipleView }>
                        <SelectMultiple
                          items={currentSelection}
                          selectedItems={removeSelection}
                          onSelectionsChange={onFavSelectionsChange}
                          />
                          {renderItems}
                    </View>

标签: javascriptreact-native

解决方案


您可以创建一个函数来呈现所需数量的项目,然后在需要的地方调用它,如下所示:

const renderItems = () => {
  return currentSelection.map(item => {
    return (
      <View key={item.value} style={{position: 'absolute', right: 10, bottom: -15}}>
        <MaterialCommunityIcons name="star" color="red" size={20}/>
      </View>
    ); //there you obviously need to put it in a return
  });
}

然后在你的组件中的某个地方调用它

{renderItems()}

你可以看看这里的例子

第二个选项将这样做:

const renderItems = data.map(item => {
  return(<Text>{item}</Text>)
})

...
{renderItems}
...

推荐阅读