我在试着设置图像。当我设置第一个图像时,它工作得很好,但是当我试图上传第二个图像时,它会创建第二个图像框,但不会在其上显示任何内容,而是将其显示在第一个图像框的顶部。我想让他们彼此分开。
我尝试通过在imgUrl函数中返回imgUrl(返回imgUrl)来直接使用blob,但它也没有在imgUrl中设置blob。一旦收到图片(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>
);
}
}发布于 2018-05-16 05:59:52
问题可能在这里,src={ this.urlFetch(pic) }函数urlFetch正在返回一个承诺,而不是实际的图像路径或数据。在componentDidMount钩子中调用此函数,并在状态中设置从后端接收到的图像,并使用该状态属性作为图像的src。
我可以看到,urlFetch函数手动修改DOM以设置映像src,这有点令人困惑,因为您正在调用的函数正在隐式地执行它的工作,而修改DOM in react根本不是一个好做法,而且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>
);
}
}https://stackoverflow.com/questions/50363169
复制相似问题