首页 文章

React-Native Image无效的prop 'source'提供给Image

提问于
浏览
0

我认为这是一个非常烦人的错误,感觉没有解决方案,但我想分享并问...我从服务器获取数据,我从那里获取图像源,我在我的移动react-native应用程序中使用相同的Image路径 .

我从服务器获取数据,如下所示:

$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 ,我怎么能解决这个问题:

警告:支柱类型失败:提供给“图像”的无效道具'源' .

1 回答

  • 2

    这不是推荐的动态图像分配方法,因为在编译捆绑包之前,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但可能会奏效 .

    如果有帮助,请告诉我

相关问题