要求`require`的调用恰好期望1个字符串文字参数,但是发现了:

时间:2018-07-30 06:17:30

标签: image react-native react-native-sectionlist

我在应用程序中具有SectionList的组件,该组件从本地json文件解析其内容。列表项具有图像和文本,并且当需要使用可变文字的图像时,会导致错误: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无法动态运行。它的参数必须是字符串。

1 个答案:

答案 0 :(得分:0)

修改: 我认为您需要使用map的解决方法

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

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

让我知道它是否有效