我有一个文件main.js,它调用组件Home之类的
<Home width = {width} }/>
我的home组件的图片类似
class Home extends Component{
render(){
return(
<View style = {{width: this.props.width/2,height:this.props.width/2 ,
borderWidth:0.5,borderColor:'#dddddd'}}>
<View style = {{flex : 1}}>
<Image
style = {{flex:1,width:null,height:null,resizeMode:'cover'}}
source = {require(this.props.source)} >
</Image>
</View>
<View style ={{flex:1 , alignItems:'flex-start',
justifyContent:'space-evenly', paddingLeft: 10}}>
<Text style = {{fontSize:14,color:'#b63838'}}> 5 bedroom </Text>
<Text style = {{fontSize:12 , fontWeight:'bold'}}>North York</Text>
<Text style = {{fontSize:12 , fontWeight:'bold'}}>$4000</Text>
</View>
</View>
);
}
}
export default Home;
图像存储在本地资产文件夹中,可以通过以下方式访问
require('../assets/Images/Houses/house6.jpeg');
必须使用不同的图像多次调用我的组件。
如何将图像路径传递到Home组件。
<Home width = {width} source = ??????/>
答案 0 :(得分:2)
您已经在家庭组件中访问了this.props.source
。
如下所述,将图像导出到文件中以导入到任何组件中。
更新:
const images = {
houseImage: require(‘../assets/Images/Houses/house6.jpeg’)
};
export default images;
主页组件
import Images from ‘@assets/images’;
<Image style = {{flex:1,width:null,height:null,resizeMode:'cover'}} source={Images.houseImage} />
答案 1 :(得分:0)
尝试这个:
class ParentClass extends Component {
construct() {
this.state = {
images : [require('../path/to/image1.png'), require('../path/to/image2.png')]
};
}
render = () => {
// Iterate through this one...
return(<Home width={width} source={this.state.images[i]});
}
}
您不能将动态的东西传递给require()函数。 在此处进一步阅读:react native use variable for image file