我有一个带有一个组件EventCard的js文件,它接受事件名称,日期,事件图像等。如果事件图像不存在,我想加载一个占位符图像。现在这个陈述看起来像这样
constructor(props){
super(props);
let imgUrl = props.image ? props.image : require("../assets/images/image.jpg");
this.state = {image: imgUrl}
}
我正在使用this.state里面的渲染源代码
source={{uri: this.state.image}}
我奇怪的是,在对占位符图像执行需求时会得到11,并且反应本机抛出错误,说'uri的值不能从Double转换为String'。
非常感谢帮助。
谢谢
使用require时,您需要直接分配图像源。
constructor(props){
super(props);
let imgUrl = props.image ? { uri: props.image } : require("../assets/images/image.jpg");
this.state = { image: imgUrl };
}
然后在你的渲染中:
source={this.state.image}
你可以这么做
constructor(props){
super(props);
let imgUrl = props.image ? props.image : null
this.state = {image: imgUrl}
}
source={imgUrl == null ? require("../assets/images/image.jpg") : this.state.image}
不要动态使用require
。本文中的详细解释:React Native - Image Require Module using Dynamic Names
经过一些研究和@Fawaz和@Haider的一些帮助,我理解要求返回一个数字。这意味着我们可以直接使用数字而不是需要而且它可以工作
<Image source={11} />
如果您有与该编号对应的任何图像,则应显示本地资源中的图像。所以当想要决定是否显示服务器发送的URL或本地资源时,就像我的情况一样。我们可以使用@Fawaz答案基本上插入一个{uri:“image-link”}或者require(“image”),其中require将被解析为一个数字,当与source一起使用时,你将放置对象或数字。根据文档的标准方法。
You can try this,
import React, {Component} from 'react';
import {StyleSheet,ImageBackground} from 'react-native';
import bgSrc from './images/bgfrm.png';
export default class Wallpaper extends Component {
constructor(props){
super(props);
let imgUrl = props.image ? props.image :bgSrc;
this.state = {image: imgUrl};
}
render() {
return (
<ImageBackground style={styles.picture} source={this.state.image}>
{this.props.children}
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
picture: {
flex: 1,
width: null,
height: null,
resizeMode: 'cover',
},
});
根据documentation,source
的<Image />
道具只占用资源的路径(本地或远程)。以下是您的示例中的外观:
import React, { Component } from 'react';
import { Image } from 'react-native';
class EventCard extends Component {
constructor(props) {
super(props);
const imgUrl = props.image || require('../assets/images/image.jpg');
this.state = { image: imgUrl };
}
render() {
return (
<Image
source={this.state.image}
/>
);
}
}
export default EventCard;