reactjs - ReactJS: TypeError: this.ref.current.method is not an function with ant design form
问题描述
class Parent extends Component {
constructor(props) {
super(props);
this.Child_A = React.createRef();
this.Child_B = React.createRef();
}
function_uses_Child_A = ()=> {
// This is working fine
this.Child_A.current.Child_A_Function()
}
function_uses_Child_B = ()=> {
// This is Does NOT work
// this.Child_A.current.Child_B_Function() is not a function
this.Child_A.current.Child_B_Function()
}
render() {
return (
<div>
<Child_A ref={this.Child_A}/>
<Child_B ref={this.Child_B}/>
</div>
);
}
}
export default Parent;
上面的代码显示了我的问题,两者都有相同的代码,但一个有效,另一个无效
这是子 A 组件:
class Child_A extends Component {
Child_A_Function = () => "Working";
render = () => <h1>Child_A</h1>
}
export default Child_A;
这是子 B 组件:
import {Form} from "antd";
class Child_B extends Component {
Child_B_Function = () => "Not Working";
render = () => <h1>Child_B</h1>
}
export default Form.create()(Child_B);
我试图调试this.Child_B.current
图像调试信息
我相信它显示了 Form.create() 数据并删除了我的数据我理解这一点,因为 Child_A 工作正常,唯一不同的是它没有 Form.create()
解决方案
这是因为Form.create()()
它是一个返回另一个组件的高阶函数。
所以
const DecoratedChild_B = Form.create()(Child_B);
DecoratedChild_B 可能有其他包装器,它变成这样:
<wrapper ref={this.Child_B}>
<Child_B/>
</wrapper>
这就是为什么你得不到你想要的。
要获取表单引用,您应该使用WrappedComponentRef
const EnhancedForm = createForm()(Form);
<EnhancedForm wrappedComponentRef={(inst) => this.formRef = inst} />
this.formRef // => The instance of Form
如果你想要一些自定义的东西,你必须为 ref func 使用其他名称
推荐阅读
- php - 使用 Symfony 启动服务器时出现 DocumentRoot 错误
- node.js - 无法读取未定义的属性“virtualMachines”
- c - 我无法理解这个#define 语句的用途
- amazon-sagemaker - SageMaker Jupyter(Lab) 中的 VIM(或其他插件)安装
- spring - 在 Spring Boot 多模块项目 fat jar 中未执行 Liquibase 脚本
- python - Keras 在 n 个批次后更新权重
- internet-explorer - 2019 年我还应该支持 Internet Explorer 吗?
- javascript - 如何循环遍历表格并将表单数据动态添加到表格中?
- sql - 多个 Google 表格/工作簿上的 SQL 联合
- php - 在 Laravel 中,统计用户并返回状态