javascript - 调用 redux-form 的 React 组件方法
问题描述
无论如何可以访问redux-form的组件方法。我希望我的上传按钮提交表单,如果用户没有选择任何文件,那么我将打开文件选择对话框。
我的代码
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)
解决方案
希望您找到了解决方案,如果没有解决方案,则不推荐使用字符串引用,您应该使用函数回调,
ref 接受一个回调函数,您可以通过该回调函数将 setter 函数传递给子级(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)
推荐阅读
- coq - 如何在假设中应用构造函数?
- python - 如何将字符串的最后一个字符替换为字母表的第一个字母?
- php - 如果产品已经在 WooCommerce 购物车中,则禁用添加到购物车按钮
- momentjs - 为什么 MMM 时刻月包含“.”?
- node.js - 当源代码更改时,带有种子随机数的玩笑测试是不可预测的,并且测试失败
- kdb - KDB - 对大型数据集的取消分组或删除进行故障排除?
- sql - 将两个源表连接到一个列中
- mongodb - 使用 Java FindIterable 访问 MongoDB 中的子文档值
- python - 在排序后的数组中查找 np 数组的 ID(或索引),其中可能包含重复元素
- arrays - 在评估不带括号的简单数学表达式时保持运算顺序