Blame view

src/components/imgCom/imgCom.js 2.16 KB
d47ac30f   Zhang Zhuo   更新组件区域选择 -张卓
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
  import React, { Component } from 'react';
  import "./imgCom.css"
  export default class imgCom extends Component {
      constructor() {
          super();
          this.state = {
              imgUrl: "",
              httpImg:"",
              base64Url:""
          }
      }
      static getDerivedStateFromProps(props,state){
          let {httpImg,imgUrl} = props;
          if(httpImg&&httpImg!==state.httpImg){
              return {
                  httpImg,
                  imgUrl
              }
          }else if(imgUrl!==state.imgUrl){
              return {
                  imgUrl
              }
          }
          return null
      }
      shouldComponentUpdate(nextProps){
          if(this.props.imgUrl !== nextProps.imgUrl){
              this.count=0;
              this.getImage(nextProps.imgUrl)
              return true
          }else{
              if(this.count===0){
                  this.count ++;
                  return true
              }else{
                  return false
              }
          }
      }
      componentDidMount(){
          this.count = 0
          if(this.state.httpImg){
              this.getImage(this.props.imgUrl)
          }
      }
      getImage(imgUrl) {
          let {httpImg} = this.state
          var xhr = new XMLHttpRequest();
          xhr.open('POST', httpImg);
          xhr.setRequestHeader('Content-Type', 'application/json');
          var data = {
              reqInfo: {
                  imgPath: imgUrl
              },
              request: "getImgDataByPath"
          }
          xhr.send(JSON.stringify(data));
          xhr.onreadystatechange =  () =>{
              if (xhr.readyState === 4) {
                  if (xhr.status === 200 || xhr.status === 304) {
                      var result = JSON.parse(xhr.responseText)
                      if(result.status === 0){
                          this.setImgUrl("data:image/png;base64,"+result.resInfo.imgData)
                      }else{
                          this.setImgUrl(require("./asstes/err.png"))
                      }
                  }
              }
          }
      }
      setImgUrl(url){
          this.setState({
              base64Url:url
          })
      }
      render() {
          let {base64Url} = this.state
          return <img src={base64Url} alt="" ></img>
      }
  }