如何在 React 组件中使用 Dropzone
2021-03-05
2114
我试图在 React 组件中使用 Dropzone。 但是它不起作用。变量 uploadfile 始终未定义。
当我选择一个文件时,会发生此错误。 错误。 TypeError:将循环结构转换为 JSON -> 从具有构造函数“HT​​MLInputElement”的对象开始 | 属性“__reactFiber$35tlapmme54”-> 具有构造函数“FiberNode”的对象 --- 属性“stateNode”关闭循环
import React, { Component, useCallback } from 'react'
import {connect} from 'react-redux'
import { createProject } from '../../store/actions/projectActions'
import {Redirect} from 'react-router-dom'
import Dropzone from 'react-dropzone';
class CreateProject extends Component {
state = {
title:'',
content:'',
uploadfile:'',
}
handleChange = (e) =>{
this.setState({
[e.target.id]: e.target.value
})
}
handleSubmit = (e) =>{
e.preventDefault();
this.props.createProject(this.state)
this.props.history.push('/')
}
onDrop = acceptedFiles => {
if (acceptedFiles.length > 0) {
this.setState({ uploadfile: acceptedFiles[0] })
}
}
handleSubmitImg = (e) =>{
e.preventDefault()
//this.props.sampleteFunction()
};
render() {
const maxSize = 3 * 1024 * 1024;
const {auth} = this.props
console.log("uploadFile"+this.uploadfile ); //It always be Undefined
if(!auth.uid) return <Redirect to="/signin" />
return (
<Dropzone
onDrop={this.onDrop}
accept="image/png,image/jpeg,image/gif,image/jpg"
minSize={1}
maxSize={maxSize}
>
{({ getRootProps, getInputProps }) => (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">
Create Project
</h5>
<div className="input-field">
<label htmlFor="title">Title</label>
<input type="text" id="title" onChange={this.handleChange}/>
</div>
<div className="input-field">
<label htmlFor="content">Project Content</label>
<textarea id="content" className="materialize-textarea" onChange={this.handleChange}></textarea>
</div>
<div className="input-field">
<button className="btn pink lighten-1 z-depth-0">Create</button>
</div>
</form>
<div {...getRootProps()}>
<input {...getInputProps()} />
{console.log("SelectedFile"+ {...getRootProps() })}
<p>Choose image File</p>
{this.uploadfile ? <p>Selected file: {this.uploadfile.name}</p> : null}
</div>
</div>
)}
</Dropzone>
)
}
}
const matchStateToProps = (state) => {
return{
auth: state.firebase.auth
}
}
const mapDispatchToProps = (dispatch) => {
return{
createProject: (project) => dispatch(createProject(project))
}
}
export default connect(matchStateToProps, mapDispatchToProps)(CreateProject)
2个回答
下面一行有错误
{this.uploadfile ? <p>Selected file: {this.uploadfile.name}</p> : null}
uploadfile 是状态变量,只能通过如下方式访问
this.state.uploadfile
Vineet Kumar
2021-03-05
尝试解析接收到的文件。
function parseFile(file) {
const updatedFile = new Blob([file], { type: file.type });
updatedFile.name = file.name;
return updatedFile;
}
以及 onDrop:
onDrop={(files) => this.onDrop((
files.map((file) => parseFile(file))
))}
Yadab
2021-03-05