【问题标题】:React Native: Image not displaying with dynamic/local URIReact Native:图像未使用动态/本地 URI 显示
【发布时间】:2019-04-11 20:53:53
【问题描述】:

所以我试图显示一个带有动态 uri/path 的图像(在初始化时它显示一个占位符图像,然后稍后更改),如下所示:

<Image source={this.state.pickedImage == null? require('./Placeholder.jpeg'):{uri: this.state.pickedImage}}/>

其中this.state.pickedImage 被初始化为null,然后使用react-native-image-pickerlaunchCameralaunchImageLibrary 进行更改,如下所示:

cameraHandler = () => {
    ImagePicker.launchCamera({title: "Pick an Image", maxWidth: 800, maxHeight: 600}, res => {
        if (res.didCancel) {
            console.log("User cancelled!");
        } else if (res.error) {
            console.log("Error", res.error);
        } else {
            this.setState({
                pickedImage:  res.uri,
                imageSize: res.fileSize,
            });
        }
    });
}}; 

(我应该提一下,我以同样的方式完全实现了launchImageLibrary,所以我真的没有理由把它放在这里。)

虽然占位符图像显示得很好,但每当我上传新图像时,&lt;Image/&gt; 似乎根本没有渲染,我只剩下一个背景。

我的尝试:

我尝试过在我的state 中初始化this.state.pickedImage 之类的操作:

pickedImage: require('./Placeholder.jpeg').uri

然后添加图片标签,如:

<Image source={{uri: this.state.pickedImage}} />

但可惜最终导致我无法渲染任何图像。

我考虑过动态绑定到require() 的路径,例如here(以及该站点上的许多地方),但据我了解,您需要知道您可能想要来自哪些潜在图像事先,如果我使用相机,我真的不能这样做。 (另外,我不能事先设置一个列表并导出用户手机上的每张图片,所以我的双手被绑在那里。)(显然,没有办法真正动态绑定到 require () 我正在寻找的方式,because the package manager doesn't work that way)

有什么方法可以渲染这些uris?任何帮助表示赞赏!

(我使用的是 react-native 0.57.4 btw)

【问题讨论】:

    标签: javascript react-native jsx react-native-image-picker


    【解决方案1】:

    原来解决方案非常愚蠢,但我所要做的就是为标签设置宽度和高度,例如:

    <Image style={{width:100,height:100}} source={this.state.pickedImage == null? require('./Placeholder.jpeg'):{uri: this.state.pickedImage}}/>
    

    我最初忽略了这个解决方案,因为我做了类似的事情:

    <Image style={{width:'100%',height:'100%'}} source={this.state.pickedImage == null? require('./Placeholder.jpeg'):{uri: this.state.pickedImage}}/>
    

    当时它不起作用,但现在它起作用了。我不知道为什么,但它现在可以工作了。如果有人知道为什么,我会非常感激知道为什么。

    【讨论】:

      【解决方案2】:

      您使用的是哪个“react-native”版本?它不适用于所有平台? require('./image.jpg') 应该可以工作,也许你的 URI 有问题。 或者尝试用Image.resolveAssetSource(source);加载

      【讨论】:

      • 我使用的是 react-native 0.57。据我所知,我认为这个版本的反应没有任何此类错误。另外,现在查找它,据我了解Image.resolveAssetSource 似乎只是将路径转换为 ​​uri,这似乎没有太大帮助。 (facebook.github.io/react-native/docs/image#resolveassetsource)
      【解决方案3】:

      我觉得你的res.uri 不行。

      在我从图库中加载图片的项目中,我有 res.node.image.uri ,如下所示:

       <Image style={styles.imageItem}
          source={{ uri: res.node.image.uri }}
       />
      

      【讨论】:

      • 我试过了,但它并没有真正起作用。如果问题是我使用的路径,那么我在上面使用的require() 会遇到错误,因为我在将pickedImage 初始化为@987654326 时使用了 exact 相同的路径@.
      • hmm.. 如果你 console.log() this.state.pickedImage 输出是什么?
      猜你喜欢
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 2018-02-03
      相关资源
      最近更新 更多