最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - if statement inside image source uri - react native - Stack Overflow

programmeradmin1浏览0评论

There is an api that sometimes send empty field for image urls and react native tell me source.uri should not be empty but I am more worried because it breaks my grid layout. I would like to use a placeholder of the same size to fix that. This is what I tried so far

<View>
    <Image source={{ !this.item.thumbnail.length ? uri: 
    item.thumbnail : {require('/assets/images/placeholder.jpg')} }} />
</View>

Could any one please help.

There is an api that sometimes send empty field for image urls and react native tell me source.uri should not be empty but I am more worried because it breaks my grid layout. I would like to use a placeholder of the same size to fix that. This is what I tried so far

<View>
    <Image source={{ !this.item.thumbnail.length ? uri: 
    item.thumbnail : {require('/assets/images/placeholder.jpg')} }} />
</View>

Could any one please help.

Share Improve this question edited Sep 11, 2018 at 2:01 Dacre Denny 30.4k5 gold badges51 silver badges66 bronze badges asked Sep 11, 2018 at 1:40 user7319004user7319004 4
  • placeholder.jog or placeholder.jpg ? – Dacre Denny Commented Sep 11, 2018 at 1:48
  • What is uri: item.thumbnail supposed to be? – Adam Commented Sep 11, 2018 at 1:51
  • @adam using flatlist and render item – user7319004 Commented Sep 11, 2018 at 1:59
  • @dacre-denny typo – user7319004 Commented Sep 11, 2018 at 2:00
Add a ment  | 

3 Answers 3

Reset to default 9

You are quite close in your attempt, but the syntax is not right. You just need to make sure that in one branch of the ternary, you return an object with a uri field, and in the other, you return the require call directly (don't wrap it as you've done in your example).

EG:

<Image
    // Note there is only a single enclosing brace here:
    source={this.item.thumbnail.length
        ? {uri: item.thumbnail}                      // Use object with 'uri'
        : require('/assets/images/placeholder.jpg')} // Or use require call directly
/>

Note: I reversed your condition which seemed backwards to me. You want to use the thumbnail when it has a non-zero length, and a placeholder otherwise, so I removed the negation.

Using a third party library solve my problem :

import ImageLoad from 'react-native-image-placeholder';

<View>
  <ImageLoad style={styles.pix} source={{uri: item.thumbnail}}/>
</View>  

This answer does not strictly fall within the scope of your question, but it might help. Why not define the source as a variable outside of the return()

Something like:

let newSauce = !this.item.thumbnail.length ? uri: 
    item.thumbnail : {require('/assets/images/placeholder.jpg')}
return(
    <View>
         <Image source={{ newSauce }} />
    </View>
)
发布评论

评论列表(0)

  1. 暂无评论