高阶组件 wrappedComponentRef 获取组件的引用

873 阅读1分钟

高阶组件 wrappedComponentRef 获取组件的引用

子组件

子组件是个form组件,使用createForm()(Childt)

import { createForm } from 'rc-form';
export class Childt extends Component {
  run = () => { console.log('我是子组件的方法')} // 方法
  render() {return (<div>我是Child</div>) }
}
export default createForm()(Childt)

父组件

此时如果使用正常的ref来调用子组件将会报错this.refs.fn is not a function; 原因:获取到的refs其实是调用form.create方法后被重新封装过了,返回的应该是一个新的对象。

调用自定义组件的时候如果想取到最初始的组件对象,需要调用一下rc-form提供的wrappedComponentRef,这个属性的返回值就是我们要的初始对象

详细的例子-核心

// 使用wrappedComponentRef

this.formRef.showDrawer() // 调用子组件身上的函数
<EditSubject wrappedComponentRef={(form) => this.formRef = form} />

普通的表单 不带create的 父调子

图片.png

图片.png

图片.png

图片.png