React Native-为具有变量的图像创建uri

时间:2018-08-23 12:09:49

标签: reactjs react-native

问题1:

如何使用链接和变量创建uri?我的示例来自API。

<Image source={{uri: 'http://www.mypage.com/'+`${val.images.filename}`}}  style={styles.imgProd} />

问题2:

我还想知道如何使用类似这样的功能来构建uri。

makeImgUrl(value) {
    if (value === '' || valueUrl === 'null') {
        return ("http://www.mypage.com/defaultimg.jpg")
    } else {
        return ("http://www.mypage.com/"+${value})
    }
}

<Image source={{uri: +makeImageUrl(val.images.filename)}}  style={styles.imgProd} />

2 个答案:

答案 0 :(得分:0)

您可以简单地添加带有+的url变量,如下所示:

<Image source={{uri: 'http://www.mypage.com/'+val.images.filename}}  style={styles.imgProd}/>

或调用函数,如:

function makeImgUrl(value) {
    if (value === '' || valueUrl === 'null') {
        return "http://www.mypage.com/defaultimg.jpg"
    } else {
        return "http://www.mypage.com/"+value
    }
}

<Image source={{ uri: makeImageUrl(val.images.filename) }}  style={styles.imgProd} />

答案 1 :(得分:0)

您错误地使用了string interpolation

let name = 'John';

console.log('Hi! I am ' + name); //ES5

console.log(`Hi! I am ${name}`)

如上所示,要么我们采用ES5方式(根本不使用反引号),要么选择ES6方式,删除单引号/双引号并替换为反引号。

因此,将我所说的应用于您的情况,如下所示

<Image source={{uri: 
`http://www.mypage.com/${val.images.filename}`}}  style={styles.imgProd} />

<Image source={{uri: 
'http://www.mypage.com/' + val.images.filename}}  style={styles.imgProd} />