The last article showed how to pull visible out by calling showModal and hideModal with a button click event. This time we will upgrade to call the events in the component directly using ref without using buttons.
import React, { useState, forwardRef, useImperativeHandle } from 'react'
function Dialog(props, ref) {
const { onSuccess, renderBtn = <span></span>, item = {} } = props
const [visible, setVisible] = useState(false)
// Modal display and hide
const showModal = () = > {
setVisible(true)}const hideModal = () = > {
setVisible(false)
}
useImperativeHandle(ref, () = > ({
showModelRef: showModal,
hideModelRef: hideModal
}))
const handleClose = () = > {
hideModal()
}
return (
<span>{React.cloneElement(renderBtn, { ... renderBtn.props, onClick: showModal })}<Modal
width={670}
footer={null}
visible={visible}
centered={true}
maskClosable={false}
onCancel={handleClose}
destroyOnClose={true}
>{/ /... }</Modal>
</span>)}export default forwardRef(Dialog)
Copy the code
First of all, introduce the forwardRef and useativeHandle
Use:
import React, { useRef } from 'react'
import Dialog from './dialog.js'
export default function App () {
const dialogRef = useRef()
/ / dialogRef. Current. ShowModelRef () to call directly using the method of ref showModelRef popup window can display ()
console.log('dialogRef---', dialogRef)
return (
<Dialog
ref={dialogRef}
/>)}Copy the code
The showModelRef() popover will show that useRef is used to call the ref current method instead of Baidu. Ha ha ha ha that’s it… Code word is not easy give azer a thumbs up!!