0

我在应用程序中有一个带有 SectionList 的组件,它从本地 json 文件中解析其内容。列表项具有图像和文本,当需要使用 varibale 的图像时,它会导致错误:calls to require expect exactly 1 string literal argument, but this was found: item.logo

我的 json 文件

{
    "algorithms":[
       {"title":"Sorting algorithms","logo":"../logos/sorting.png"},
       {"title":"Graph theory","logo":"../logos/graph.png"},
       {"title":"Strings","logo":"../logos/strings.png"},
       {"title":"Greedy technique","logo":"../logos/greedy.png"},
       {"title":"Dynamic programming","logo":"../logos/dp.png"}
    ],
    "datastructures":[
       {"title":"Trees","logo":"../logos/tree.png"},
       {"title":"Lists","logo":"../logos/list.png"},
       {"title":"Tries","logo":"../logos/trie.png"},
       {"title":"Stack and Queue","logo":"../logos/stack.png"},
       {"title":"Hash Tables","logo":"../logos/hashtable.png"}
     ] 
}

renderItem功能

renderItem = ({item}) => {
    return(
        <TouchableWithoutFeedback onPress={()=>this.props.navigation.navigate('List')}>
            <View style={styles.itemHolder}>
                <Image resizeMode="center" style={styles.itemLogo} source={require(item.logo)}/>
                <View style = {styles.itemNameHolder}>
                    <Text style = {styles.itemName}>{item.title}</Text>
                </View>
                <View style={styles.itemPointer}>
                    <Image style={{width:50,height:50,}} source={require('../icons/right-arrow.png')}/>
                </View>
                <Divider/>
            </View>
        </TouchableWithoutFeedback> 
    );
}

已编辑

js中的函数require不能动态工作。它的参数必须是字符串。

4

1 回答 1

0

编辑:我认为您需要使用地图的解决方法

首先,您需要找到一种方法使徽标格式成为这样

const data = [
   {"title":"Sorting algorithms","logo": require('../logos/sorting.png')},
   {"title":"Graph theory","logo": require('../logos/graph.png')},
]

然后,当您想使用它时,只需这样做

render() {
  return (
    <View>
      {data.map((item) => {
        <View>
          <Image
           style={styles.image}
           source={item.logo}
          />
        </View>
      })}
    </View>
  );
}

让我知道它是否工作

于 2018-07-30T09:46:42.400 回答