项目使用antd-react
组件库。用Form.create
想要拿到ref
,即想拿到子组件的数据和方法,可以使用wrappedComponentRef
以下为官方举例
class CustomizedForm extends React.Component { ... }
// use wrappedComponentRef
const EnhancedForm = Form.create()(CustomizedForm);
<EnhancedForm wrappedComponentRef={(form) => this.form = form} />
this.form // => The instance of CustomizedForm
一开始被形参form
误导了,一直以为拿到的ref
只是antd-react
组件库封装的form
实例。下面自己敲了下代码,其实拿到的this.form
相当于子组件
class ChildForm extends React.Component {
say() {
console.log('hello')
}
...
}
const Child = Form.create()(ChildForm);
class Parent extends React.Component {
...
getChild() {
console.log(this.form.props.form)
console.log(this.form.say)
// 以上两个都可以拿到
// 再consle.log(this.form)
console.log(this.form)
// 发现拿到就是`ChildForm`本身
}
react() {
return (
<div>
<button onclick={this.getChild}>click</button>
<Child wrappedComponentRef={(form) => this.form = form} />
</div>
)
}
}
以上个人总结,可能有误。