使用react-dropzone(https://www.npmjs.com/package/react-dropzone)并将文件记录到控制台,但无法获取图像预览以填充状态更改。知道我做错了吗?
export default class JoinForm extends Component {
constructor(props) {
super(props)
this.state = {
imageFiles: []
}
}
onDrop(imageFiles) {
this.setState({
imageFiles: imageFiles
})
console.log(imageFiles)
}
render() {
return(
<form className='join-form' ref='joinForm' autoComplete='off'>
<Dropzone
onDrop={this.onDrop}
className='dropzone'
activeClassName='active-dropzone'
multiple={false}>
<div>Drag and drop or click to select a 550x550px file to upload.</div>
</Dropzone>
{this.state.imageFiles.length > 0 ? <div>
<h2>Uploading {this.state.imageFiles.length} files...</h2>
<div>{this.state.imageFiles.map((file) => <img src={file.preview} /> )}</div>
</div> : null}
</form>
)
}
};
答案 0 :(得分:12)
正确答案:成为一个假人,忘了绑这个。
<Dropzone
onDrop={this.onDrop.bind(this)} //<= Here
className='dropzone'
activeClassName='active-dropzone'
multiple={false}
style={imageUploadStyle}>
<div>Drag and drop or click to select a 550x550px file to upload.</div>
</Dropzone>
答案 1 :(得分:8)
您正在imageFiles
中存储文件,但在render
方法中,您要映射this.state.files
数组。
变化:
<div>{this.state.files.map((file) => <img src={file.preview} /> )}</div>
致:
<div>{this.state.imageFiles.map((file) => <img src={file.preview} /> )}</div>
或者,因为您有这个常量const files = this.state.imageFiles
,您可以将上述语句更改为:
<div>{files.map((file) => <img src={file.preview} /> )}</div>
答案 2 :(得分:1)
将渲染功能更改为imageFiles
render() {
const files = this.state.imageFiles
return(
<form className='join-form' ref='joinForm' autoComplete='off'>
<Dropzone
onDrop={this.onDrop}
className='dropzone'
activeClassName='active-dropzone'
multiple={false}>
<div>Drag and drop or click to select a 550x550px file to upload.</div>
</Dropzone>
{this.state.imageFiles.length > 0 ? <div>
<h2>Uploading {this.state.imageFiles.length} files...</h2>
<div>{this.state.imageFiles.map((file) => <img src={file.preview} /> )}</div>
</div> : null}
</form>
)