[英]Calling React component method of redux-form
无论如何可以访问redux-form的组件方法。 我希望我的上传按钮提交表单,如果用户没有 select 任何文件,那么我将打开文件 select 对话框。
我的代码
UploadModal.js
import React from 'react';
import Form from './components/Form';
class UploadModal extends React.Component {
constructor(props) {
super(props)
this.onSubmit = this.onSubmit.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
onSubmit() {
// call open file select dialog if haven't select any file
this.refs.form.submit();
}
handleSubmit(values) {
//handling submit
}
render() {
return (
<div>
<p>Upload files</p>
<Form ref="form" onSubmit={this.handleSubmit} />
<Button onClick={this.onSubmit}>Upload</Button>
</div>
)
}
}
表单.js
import React from 'react';
import { reduxForm } from 'redux-form';
import Dropzone from 'react-dropzone';
class Form extends React.Component {
constructor(props) {
super(props)
}
onOpenDialog() {
// I want to access this method from Upload Modal
this.refs.dropZone.open();
}
render() {
return (
<div>
<Dropzone ref="dropZone">
<p>Please select file to upload</p>
</Dropzone>
</div>
)
}
export default reduxForm({
form: 'upload',
fields: ['file'],
})(Form)
希望您找到了解决方案,如果不是这里的解决方案,则不推荐使用字符串引用,您应该使用 function 回调,
ref 接受一个回调 function 通过它您可以通过将设置器 function 传递给子级(setDropZoneRef)来设置父级中的 dropzoneref
这是相同的代码
import React from "react";
import Form from "./components/Form";
class UploadModal extends React.Component {
constructor(props) {
super(props);
//add a ref value to your state and a setter to set the ref
this.setDropZoneRef = this.setDropZoneRef.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
onSubmit() {
// call open file select dialog if haven't select any file
//here use the formref you've set
this.formRef.submit();
}
setDropZoneRef (ref) {
this.dropZoneRef = ref
}
handleSubmit(values) {
//handling submit
}
render() {
return (
<div>
<p>Upload files</p>
<Form ref={ref => (this.formRef = ref)} onSubmit={this.handleSubmit} />
<Button onClick={this.onSubmit}>Upload</Button>
</div>
);
}
}
import React from 'react';
import { reduxForm } from 'redux-form';
import Dropzone from 'react-dropzone';
class Form extends React.Component {
constructor(props) {
super(props)
}
onOpenDialog() {
// I want to access this method from Upload Modal
// this.refs.dropZone.open();
}
render() {
return (
<div>
<Dropzone ref={this.props.setDropZoneRef}>
<p>Please select file to upload</p>
</Dropzone>
</div>
)
}
export default reduxForm({
form: 'upload',
fields: ['file'],
})(Form)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.