ReactJS: TypeError: this.ref.current.method is not a function with ant design form
ReactJS: TypeError: this.ref.current.method is not a 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
image debug info
我相信它显示了 Form.create() 数据并删除了我的
我理解这一点,因为 Child_A 工作正常,唯一不同的是它没有 Form.create()
这是因为 Form.create()()
是一个高阶函数,returns 另一个组件。
所以
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 函数使用其他名称
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
image debug info
我相信它显示了 Form.create() 数据并删除了我的 我理解这一点,因为 Child_A 工作正常,唯一不同的是它没有 Form.create()
这是因为 Form.create()()
是一个高阶函数,returns 另一个组件。
所以
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 函数使用其他名称