gpt4 book ai didi

javascript - React dropzone 图像未在模板上更新

转载 作者:行者123 更新时间:2023-11-28 05:52:09 25 4
gpt4 key购买 nike

我使用了 React dropzone 组件来上传多个图像,但图像预览未显示在我的模板上。文件显示在控制台上。我哪里做错了?我从这里使用了这个组件https://github.com/okonet/react-dropzone 。让我知道我还需要提供什么来仔细研究这个问题。提前感谢您的帮助。我们将不胜感激您的帮助。

import React from 'react';
import Dropzone from 'react-dropzone';

export default class DropzoneDemo extends Dropzone {
constructor(props) {
super(props);
this.state = {
files: [],
style: {},
};
}

componentDidMount() {
this.state.style = {
backgroundImage: (`url(${this.props.img})`),
};
this.state.files = [];
}

componentDidUpdate() {
if (this.state.files.length) {
this.state.style = {
backgroundImage: (`url(${this.state.files[0].preview})`),
};
} else {
this.state.style = {
backgroundImage: (`url(${this.props.img})`),
};
}
}

onDrop(files) {
console.log(this.state.files);
this.state.files = files;
}

render() {
const emptyStyle = {
backgroundImage: 'none',
};
return (
<div>
<Dropzone onDrop={this.onDrop} style={emptyStyle} >
<div className='wrap-to-drag-img' style={this.state.style}></div>
</Dropzone>
</div>
);
}
}

最佳答案

不要像React中那样直接更新this.state

this.state.style = { // this is bad
backgroundImage: (`url(${this.state.files[0].preview})`),
};

改为在 render() 中设置样式

render() {
const bgImage = this.state.files.length ?
`url(${this.state.files[0].preview})` :
`url(${this.props.img})`;
const bgStyle = {
backgroundImage: bgImage
};

const emptyStyle = {
backgroundImage: 'none',
};
return (
<div>
<Dropzone onDrop={this.onDrop} style={emptyStyle} >
<div className='wrap-to-drag-img' style={bgStyle}></div>
</Dropzone>
</div>
);
}

关于javascript - React dropzone 图像未在模板上更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37994536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com