有一个api有时会发送空白字段的图像网址和反应原生告诉我source.uri不应该是空的但我更担心,因为它打破了我的网格布局。我想使用相同大小的占位符来解决这个问题。这是我到目前为止所尝试的
<View>
<Image source={{ !this.item.thumbnail.length ? uri:
item.thumbnail : {require('/assets/images/placeholder.jpg')} }} />
</View>
可以请任何人帮忙。
您的尝试非常接近,但语法不正确。你只需要确保在三元组的一个分支中,你返回一个带有uri
字段的对象,而在另一个分支中,你直接返回require
调用(不要像你在你的例子中那样包装它)。
例如:
<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
/>
注意:我改变了你的情况,这似乎是我的倒退。您希望在长度非零时使用缩略图,否则使用占位符,因此我删除了否定。
使用第三方库解决我的问题:
import ImageLoad from 'react-native-image-placeholder';
<View>
<ImageLoad style={styles.pix} source={{uri: item.thumbnail}}/>
</View>
这个答案并不严格属于您的问题范围,但它可能有所帮助。为什么不将源定义为return()
之外的变量
就像是:
let newSauce = !this.item.thumbnail.length ? uri:
item.thumbnail : {require('/assets/images/placeholder.jpg')}
return(
<View>
<Image source={{ newSauce }} />
</View>
)