简体   繁体   English

如何在React Native中显示来自数组的base64图像

[英]How to display base64 images from array in React Native

I'm pretty new on react-native and I am working on an app that communicates between two user using socket.io 我在react-native上还很新,我正在开发一个使用socket.io在两个用户之间通信的应用程序

User 1 send à picture to User 2 which should be displayed on User 2 screen : a new container is created on the screen each time User 1 send a picture but nothing is inside... 用户1向用户2发送à图片,该图片应显示在用户2的屏幕上:用户1每次发送图片时,都会在屏幕上创建一个新容器,但里面什么也没有...

I use base64 format to store each newPicture in the array newPictures[]. 我使用base64格式将每个newPicture存储在数组newPictures []中。

Here is the code of User 2. I receive the base64 string on the console.log(newPictures) so everything else seems to be working, except the rendering of the picture. 这是用户2的代码。我在console.log(newPictures)上收到base64字符串,因此除显示图片外,其他所有内容似乎都在工作。

Thank you for your help ! 谢谢您的帮助 !

export default class DashboardArtificial extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newPicture: "",
      newPictures: []
    };
   }

componentDidMount() {
this.socket.on("new picture", newP => {
  this.setState({ newPictures: [...this.state.newPictures, newP] });
  setTimeout(() => {
    this.setState({
      curTime: new Date().toLocaleString()
    })
  }, 1000);
});
}

render() {
 const newPictures = this.state.newPictures.map(newPicture => {
   console.log(newPicture);
    return (
     <Image
       style={styles.arrayPictures}
       key={newPicture}
       source={{uri: 'data:image/png;base64,{newPicture}'}}
      />
    )
  });

return (
  {newPictures}
  )

You want to use the back ticks to do this, not single quotes. 您要使用反勾号(而不是单引号)来执行此操作。 The back tick is a delimiter in ES6 for template literals which can contain placeholders such as {newPicture} which are passed as function. 反勾是ES6中模板文字的定界符,其中可以包含占位符,例如{newPicture},它们是作为函数传递的。

 <Image
   style={styles.arrayPictures}
   key={newPicture}
   source={{uri: `data:image/png;base64,${newPicture}`}}
  />

If you want to read more about the back tick you can do so here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals 如果您想阅读更多有关反向勾号的信息,可以在这里进行: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM