需求:父组件里有个子组件,子组件是个表单,父组件要调用子组件的方法。
操作:使用常规的refs.child.fn(), 结果试了好几次没成功,差点怀疑人生,
坑:后来发现是因为子组件用了rc-form的createForm方法把子组件给封装了一下
"react": "^17.0.2",
"antd-mobile": "^2.3.4",
子组件:
import { createForm } from ‘rc-form’;
export class Childt extends Component {
run = () => { console.log(‘我是子组件的方法’)} // 方法
render() {return (
我是Child
) }
}
export default createForm()(Childt)
父组件:
此时如果使用正常的ref来调用子组件将会报错this.refs.fn is not a function;
原因:获取到的refs其实是调用form.create方法后被重新封装过了,返回的应该是一个新的对象。
调用自定义组件的时候如果想取到最初始的组件对象,需要调用一下rc-form提供的wrappedComponentRef,这个属性的返回值就是我们要的初始对象
// 使用wrappedComponentRef
<Childt wrappedComponentRef={(form)=>{this.childt = form}}>
点击
click=()=>{
this.childt.run() // 成功
}