前提知识点
useImperativeHandle
常与forwardRef
和ref
一起应用,所以须要了解后两者的根底用法。能够通过以下两个示例代码,疾速理解ref
和forwardRef
的应用办法。
- Demo1: 在Class和Functional函数中应用ref .该示例展现了ref的用法,同时表明不通过
forwardRef
封装的子组件,无奈将ref
传给父组件。 - Demo2: farwardRef转发ref.该示例展现了farwardRef的用法,父组件
ForwardButton
胜利获取到子组件RefInFunctionalComponent
的ref
useImperativeHandle
官网说
useImperativeHandle customizes the instance value that is exposed to parent components when using ref
怎么了解呢?
当父组件通过forwardRef
属性,失去子组件的ref
时,它只失去一个可读的对象。而useImperativeHandle
配合forwardRef
来应用,则给予了批改ref
的能力,比方为ref
减少自定义办法。
这种在父组件中间接调用子组件ref
函数的办法,一点都不React,所以React并不举荐。然而为了不便第三方库的开发,则须要提供这种自定义ref
的能力。
咱们在Demo2的根底上批改一下代码,看看useImperativeHandle
如何工作。
批改子组件RefInFunctionalComponent
,新增useImperativeHandle
代码块,自定义getContent
办法,如下:
const RefInFunctionalComponent = (props, ref) => { const innerRef = useRef(null) useImperativeHandle(ref, () => ({ getContent: () => innerRef.current.innerText })) const handleClick1 = () => { console.log(ref.current.innerText) } return <button ref={innerRef} onClick={handleClick1}>{props.children}</button>}const ForwardButton = forwardRef(RefInFunctionalComponent)
在父组件中应用ForwardButton
:
const App = () => { const ref = useRef(null) const handleClick = () => { console.log(ref.current.getContent()) // 按钮1 } return ( <div className="wrapper"> <ForwardButton ref={ref}>按钮1</ForwardButton> <button onClick={handleClick}>获取button1</button> </div> );};
Demo3:残缺示例代码。
参考
- When to use useImperativeHandle