将base64字符串在React中转换回图像

问题描述 投票:0回答:1

我正在尝试将应用程序后端服务上已更改为base64的图像转换回前端上的图像,但这样做似乎会碰壁。这就是我的代码:

PhotoContainer.jsx

class PhotoContainer extends React.Component {

    constructor(props, context) {
      super(props, context);
      this.state = { photo: null };
    }

    async getUserPhoto(accessToken) {
      try {
        const photoResp= await requestAWSGet('path/to/api', undefined, accessToken);
        CachingService.setData('photo', photoResp);
        this.setState({ photo: photoResp});
      } catch (err) {
        log.error('AWSPost /api error:', err);
        throw err;
      }
    }

    render() {
      return (
          <PhotoComponent photo={this.state.photo} />
      );
    }
}

export default PhotoContainer

PhotoComponent.jsx

const PhotoComponent = props => (
    <>
        {`data:image/png;base64,${props.photo}`} alt={'photo'}
    </>
);

export default PhotoComponent;

[我将调用PhotoContainer,jsx的组件的示例

class ExampleComponent extends React.Component {
  render() {
    return (
         <Container>
                <Card>
                    <Card.Img src={<PhotoContainer />} alt={'photo'} />
                    <Card.Body>
                         <p>Some text</p>
                    </Card.Body>
                </Card>
            </Container>
    );
  }
}

export default ExampleComponent;

我是不是在组件中以某种方式使用了转换行,或者我设置容器的方式存在更深的问题?

reactjs base64 react-component
1个回答
1
投票

您需要以这种方式重构PhotoComponent

const PhotoComponent = props => (
    props.photo ? <Card.Img
      src={`data:image/png;base64,${props.photo}`}
      alt={'photo'}
    /> : ''
);

导出默认PhotoComponent;

ExampleComponent将只需要实例化PhotoContainer

class ExampleComponent extends React.Component {
  render() {
    return (
         <Container>
                <Card>
                    <PhotoContainer />
                    <Card.Body>
                         <p>Some text</p>
                    </Card.Body>
                </Card>
            </Container>
    );
  }
}

export default ExampleComponent;

您可以按原样保留PhotoContainer。

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.