我试图设置图像。当我设置第一个图像时它工作正常,但是当我尝试上传第二个图像时,它会创建第二个图像框,但不会在其上显示任何内容,而是将其显示在第一个图像框的顶部。我希望他们彼此分开。
我试图通过在showImage函数中返回imgUrl(返回imgUrl)直接使用blob,但它也没有在img src中设置blob。 一旦收到pic(URL),我怎样才能在每个框中分别循环并设置所有图像?
class Card extends Component {
constructor({props, pic, token}) {
super(props, pic, token);
this.state = {
pic: pic
};
readResponseAsBlob(response) {
return response.blob();
}
validateResponse(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
logError(error) {
console.log('Looks like there was a problem: \n', error);
}
showImage(responseAsBlob) {
var container = document.getElementById('images');
var imgElem = container.getElementsByTagName('img')[0];
var imgUrl = URL.createObjectURL(responseAsBlob);
imgElem.src = imgUrl;
console.log(imgUrl);
}
urlFetch(data) {
fetch(data, {
headers: new Headers({
'authorization': `Bearer ${this.props.token}`,
'Content-Type': 'application/json'
})
})
.then(this.validateResponse)
.then(this.readResponseAsBlob)
.then(this.showImage)
.catch(this.logError);
}
render() {
const { pic } = this.state;
return (
<a style={{width: 200, height: 250}} className='tc dib br3 ma2 pa2 grow bw2 shadow-5'>
<div id='images'>
<img style={{width: 175, height: 175}} className='tc myimage br3' alt='none' src={ this.urlFetch(pic) }/>
</div>
</a>
);
}
}
答案 0 :(得分:2)
问题可能在这里src={ this.urlFetch(pic) }
函数urlFetch
正在返回一个promise而不是实际的图像路径或数据。
在componentDidMount
挂钩中调用此函数,并设置从状态后端接收的图像,并将该状态属性用作图像的src
。
我可以看到urlFetch
函数手动修改DOM来设置图像src,这有点令人困惑,因为你调用的函数是隐式执行它的工作并且修改反应中的DOM不是一个很好的做法全部和var imgElem = container.getElementsByTagName('img')[0];
只会修改第一张图片,因为您收到容器中的第一张img
我还建议渲染各个组件中的每个图像,声明一个状态属性,该属性将保存图像的src
,获取服务器的图像,然后更新状态。
class Card extends Component {
constructor({props, token}) {
super(props, token);
this.state = {
src: ''
};
}
readResponseAsBlob = (response) => {
return response.blob();
}
showImage = (responseAsBlob) => {
this.setState({ src: URL.createObjectURL(responseAsBlob) });
}
componentDidMount() {
this.urlFetch(this.props.pic)
}
logError(error) {
console.log('Looks like there was a problem: \n', error);
}
urlFetch(data) {
fetch(data, {
headers: new Headers({
'authorization': `Bearer ${this.props.token}`,
'Content-Type': 'application/json'
})
})
.then(this.validateResponse)
.then(this.readResponseAsBlob)
.then(this.showImage)
.catch(this.logError);
}
render() {
const { src } = this.state;
return (
<a style={{width: 200, height: 250}} className='tc dib br3 ma2 pa2 grow bw2 shadow-5'>
<div id='images'>
<img style={{width: 175, height: 175: display: src ? 'block': 'none'}} className='tc myimage br3' alt='none' src={ src }/>
</div>
</a>
);
}
}