我认为这是一个非常烦人的错误,感觉好像没有解决方案,但我想共享和询问。.我从服务器获取数据,从那里获取图像源,并且在我的移动react- native应用程序中使用相同的图像路径。
我这样从服务器获取数据:
$id = $request->userid; $items = DB::table('item_user')->where('user_id', $id)->latest()->get(); $new = new Collection(); foreach($items as $item){ $new[] = array( ... , 'picturePath' => 'require'."('./". $item->picturePath ."')" ); } return $new;
在前端,我尝试渲染,并在本地保存这些图像。所以当我在本地使用它时:
require(’./ images / …’)
它有效..但是这样不起作用:
_renderItem = ({item}) => { return( <View> <Image source={ item.picturePath } style={{width: 15, height: 15}}/> </View> ); }; render(){ return( <View> <FlatList data={this.state.items} renderItem={this._renderItem} keyExtractor={this._keyExtractor} /> </View> ); }
我知道error如何解决这个问题:
error
警告:道具类型失败:提供给“图片”的道具“源”无效。
这不是推荐的动态分配图像的方法,因为在编译包之前,React Native必须知道所有图像源。
根据文档,这是一个如何动态加载图像的示例:
// GOOD <Image source={require('./my-icon.png')} />; // BAD var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive'; <Image source={require('./' + icon + '.png')} />; // GOOD var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png'); <Image source={icon} />;
https://facebook.github.io/react- native/docs/images.html
希望能帮助到你
编辑:如果您知道所有可以加载的图像,则可以尝试如下操作:
// Create a file containing the references for your images // images.js const images = { logo: { uri: require('your-image-path/logo.png') }, banner: { uri: require('your-image-path/banner.png') } } export { images }; //YourComponent.js import { images } from 'yourImagesPath'; // for this test, expected to return [ { name: logo }, { name: banner} ] const imagesFromTheServer = (your fetch); imagesFromTheServer.map(image => { if (!images[image]) { return <Text>Image not found</Text>; } return <Image source={images[image].uri} />; // if image = logo, it will return images[logo] containing the require path as `uri` key });
这很hacky,但可能会起作用。
让我知道是否有帮助