[英]How to hook up React Dropzone & Redux form
我正在嘗試使用 redux 表單連接一個 dropzone 組件,但無濟於事。 當提交我的表單並呈現 MyFormReview 組件時,Redux 商店中的 formValues 似乎沒有保存文件,因此不會呈現。 我找過類似的帖子,但看不出我哪里出錯了。 在此先感謝您的幫助,如果您需要更多信息,請告訴我!
我沒有包含父表單組件的代碼,因為它只是在 MyForm 和 MyFormReview 之間呈現。
提前謝謝了。
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { reduxForm, Field } from 'redux-form';
import Dropzone from './Dropzone';
class MyForm extends Component {
render() {
return (
<form onSubmit={this.props.handleSubmit(this.props.onFormSubmit)} >
<div className="flex flex-column">
<div className="flex center w-50 mb2">
<Field
name="files"
component={Dropzone}
/>
</div>
<div>
<Link to="/dashboard">
<Button>Cancel</Button>
</Link>
<button primary type="submit">
Review
</button>
</div>
</div>
</form>
);
}
};
export default reduxForm({
validate,
form: 'myForm',
destroyOnUnmount: false
})(MyForm);
onFormSubmit 屬性用於在表單的審查和編輯呈現之間切換(以便用戶可以確認他/她的輸入) onFormSubmit={() => this.setState({ showFormReview: true})}
這是 Dropzone 組件:
import React, {Component} from 'react';
import {DropzoneArea} from 'material-ui-dropzone';
class Dropzone extends Component{
constructor(props){
super(props);
this.state = {
files: []
};
}
handleChange(files){
this.setState({
files: files
});
}
render(){
return (
<DropzoneArea
acceptedFiles = {['image/*']}
filesLimit = {10}
dropzoneText="upload your images here!"
onChange={this.handleChange.bind(this)}
/>
)
}
}
export default Dropzone;
這是 MyFormReview 組件:
const MyFormReview = ({ onCancel, formValues, submitForm, history }) => {
const reviewFields = () => {
return (
<div className="ba1 ma1" key={"files"}>
<label>"Files"</label>
<div>{formValues["files"]}</div>
</div>
)
});
return (
<div>
<h3>Please confirm your entries</h3>
{reviewFields}
<button className = "yellow darken-3 white-text btn-flat" onClick={onCancel}>
Back
</button>
<button
className = "green white-text right btn-flat"
onClick={() => submitForm(formValues, history)}
>
Send Survey
</button>
</div>
);
};
function mapStateToProps(state) {
return {formValues: state.form.myForm.values};
}
export default connect(mapStateToProps, actions)(withRouter(MyFormReview));
對於偶然發現這篇文章的任何人,這是我的解決方案:
在 Dropzone 組件中,handleChange 變為:
handleChange(files){
this.setState({
files: files
});
this.props.input.onChange(files)
}
在 myFormReview 中,我可以在 reviewFields function 中插入以下 if 語句來預覽圖像。
const reviewFields = _.map(formFields, ({name, label}) => {
if(name === "files"){
return <div>{_.map(formValues[name], (file) => <img alt={file.name} src={URL.createObjectURL(file)} /> )}</div>
}
else{
return (
<div className="ba1 ma1" key={name}>
<label>{label}</label>
<div>{formValues[name]}</div>
</div>
)
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.