使用场景:需要重复触发子组件弹窗或者需要在子组件修改值的时候可以采用调用子组件身上特定方法执行操作。
在次介绍一下最新hooks的操作和旧版本class组件调用方式
一.Hooks api调用方式
需要用到的Api:useRef useImperativeHandle forwardRef
简单说明:
1.useRef: 用于获取元素的原生DOM或者获取自定义组件所暴露出来的ref方法(父组件可以通过ref获取子组件,并调用相对应子组件中的方法)
2.useImperativeHandle:在函数式组件中,用于定义暴露给父组件的ref方法。
3.forwardRef:将ref父类的ref作为参数传入函数式组件中,本身props只带有children这个参数,这样可以让子类转发父类的ref,当父类把ref挂在到子组件上时,子组件外部通过forwrardRef包裹,可以直接将父组件创建的ref挂在到子组件的某个dom元素上
实例:
父组件
export default () => {
const childRefs:any = useRef(null);
//编辑列表
const edictRow = (text:DataType) => {
//打开编辑弹窗 调用子组件身上的方法打开
childRefs.current.openModal();
}
return <>
<EditTableCom ref={childRefs}/>
<button onClick={edictRow }>打开编辑框</button>
</>
}
子组件
import React, { useState,useImperativeHandle, forwardRef } from 'react';
import { Modal } from 'antd';
export default forwardRef((props:any,ref:any) => {
const [visible, setVisible] = useState(false);
//隐藏弹窗
const hideModa = () => {
setVisible(false);
};
//监听props.openModel值的变化
//打开弹窗
useImperativeHandle(ref, () => ({
openModal: (newVal: boolean) => {
console.log(ref,newVal)
setVisible(true);
}
}));
return (
<>
<Modal
title="Modal"
visible={visible}
onOk={hideModa}
onCancel={hideModa}
okText="确认"
cancelText="取消"
>
<p>Bla bla ...</p>
<p>Bla bla ...</p>
<p>Bla bla ...</p>
</Modal>
</>
);
});
二.class组件调用方式
父组件
export default class PageConfiguration extends Component<any,any>{
constructor(props:any) {
super(props);
this.childRefs = React.createRef();
this.data = []
}
handleClick = () => {
this.childRefs.current.openModal(true)
}
render(): React.ReactNode {
return (<>
<EditTableCom ref={ this.childRefs}/>
<button onClick={this.handleClick}>Trigger Child Event</button>
</>);
}
}
子组件
import React, { Component } from 'react';
import { Modal } from 'antd';
interface InterState{
visible:boolean
}
export default class ParentCmp extends Component<any, any>{
constructor(props:InterState) {
super(props);
// 创建Ref
this.state = {visible:false}
}
//隐藏弹窗
hideModal = () => {
this.setState({
visible:false
})
};
//监听props.openModel值的变化
//打开弹窗
openModal = (newVal: boolean) => {
this.setState({
visible:newVal
})
}
render() {
return (
<Modal
title="Modal"
visible={this.state.visible}
onOk={this.hideModal}
onCancel={this.hideModal}
okText="确认"
cancelText="取消"
>
<p>Bla bla ...</p>
<p>Bla bla ...</p>
<p>Bla bla ...</p>
</Modal>
);
}
};