在项目中,有很多交互效果是实现弹窗功能,当我们将弹窗封装成组件后,要在父组件中点击打开子组件,可以有两种办法:
方法1:可以在父组件中修改弹窗的visible属性,然后传给子组件弹窗,打开子组件(不推荐)。
方法2:可以在子组件弹窗中写修改visible属性的方法,然后父组件点击事件调用子组件方法打开弹窗(推荐)
在react中class写法和hook的写法还是有区别的,接下来我通过简单的demo介绍一下这两种写法。(用的是antd组件库)
一、class写法
父组件代码
import './App.css';
import {Button} from "antd";
import DemoModal from "./component/demoModal"
import React, {Component} from 'react';
class App extends Component {
render() {
return (
<div className="App">
<Button onClick={()=>{
this.demoModal.isShow()
}}>弹窗按钮</Button>
<DemoModal ref={(ref)=>this.demoModal=ref}></DemoModal>
</div>
);
}
}
export default App;
子组件代码
import React, {Component} from 'react';
import {Modal} from "antd";
class DemoModal extends Component {
constructor(props) {
super(props);
this.state={
visible:false
}
}
componentDidMount() {
}
//控制弹窗方法
isShow=()=>{
let visible=this.state.visible;
this.setState({visible:!visible},()=>{
console.log(this.state.visible)
})
}
render() {
return (
<div>
<Modal
open={this.state.visible}
onOk={()=>{this.setState({visible:false})}}
onCancel={()=>{this.setState({visible:false})}}
>
这是子组件弹窗!
</Modal>
</div>
);
}
}
export default DemoModal;
这里父组件在子组件上通过ref={ref=>this.demoModal=ref}拿到子组件实例,然后点击按钮通过this.demoModal调用子组件中的isShow方法实现弹窗的控制。
二、Hook写法
在hook中需要注意,因为函数式组件没有生命周期以及状态,也不会被实例化,所以如果还是像class中那样去获取实例是获取不到的;这里可以用useRef,通过.current去实现。
我们引入useRef
//父组件
function App() {
const demoModal = useRef();
return (
<div className="App">
<Button onClick={()=>{console.log(demoModal)}}>弹窗按钮</Button>
<DemoModal ref={demoModal}></DemoModal>
</div>
);
}
export default App;
//子组件弹窗
const DemoModal = () => {
const [visible,setVisible] = useState(false);
const isShow = () =>{
setVisible(!visible)
}
return (
<Modal
open={visible}
onOk={()=>{setVisible(false)}}
onCancel={()=>{setVisible(false)}}
>
这是子组件弹窗!
</Modal>
);
};
export default DemoModal;
我们来看一下点击按钮后的打印内容,结果是undefined,这是为什么呢?原因就是因为子组件也是函数式组件,不会被实例化,必然拿不到子组件的属性和方法,这里如何去解决呢?
解决办法:可以在子组件中引入forwardRef和useImperativeHandle,通过forwardRef搭配useImperativeHandle方式实现类似class中的写法,通过控制子组件中的isShow方法控制弹窗。
forwardRef将子组件包裹起来,传入ref,子组件内部通过useImperativeHandle方法类似于抛出的形式将isShow方法抛出,让父组件拿到isShow方法,具体代码如下:
父组件代码
function App() {
const demoModal = useRef();
return (
<div className="App">
<Button onClick={() => {
demoModal.current.isShow();
console.log(demoModal)
}}>弹窗按钮</Button>
<DemoModal ref={demoModal}></DemoModal>
</div>
);
}
export default App;
子组件代码
import React, {forwardRef, useImperativeHandle, useState} from 'react';
import {Modal} from "antd";
const DemoModal = forwardRef((props,ref) => {
const [visible,setVisible] = useState(false);
//抛出isShow方法
useImperativeHandle(ref,()=>({
isShow(){
setVisible(!visible)
}
}))
return (
<Modal
open={visible}
onOk={()=>{setVisible(false)}}
onCancel={()=>{setVisible(false)}}
>
这是子组件弹窗!
</Modal>
);
});
export default DemoModal;
这里我们看一下打印的结果,可以看到 current不再是undefined,这样我们可以在父组件中通过demoModal.current.isShow()去调用子组件中的isShow方法进而控制弹窗。
菜鸟一枚,有什么疏漏点欢迎各位大佬评论进行补充~