ImperativeHandle Hook
一、ImperativeHandle Hook
1、情景想象
如果某种情况下你需要手动触发某个组件内部的方法时,你会怎么做呢?
很容易想到使用ref
调动该组件的事件即可,但是这里使用的是类组件,学习了hook后我们发现函数组件更加好用,那么我们怎么能够调用函数组件中的事件呢?
import React, { useRef } from 'react'
class Test extends React.Component {
method() {
console.log("Test method called");
}
render() {
return <h1>Test Component</h1>
}
}
export default function App() {
const testRef = useRef();
return (
<div>
<Test ref={testRef} />
<button onClick={() => {
testRef.current.method();
}}>点击调用Test组件的method方法</button>
</div>
)
}
2、功能实现
要知道我们是无法直接给函数组件添加ref
的,所以这里我们使用到前面学习到的知识,使用ref转发。
import React, { useRef, useImperativeHandle } from 'react'
function Test(props, ref) {
//如果不给依赖项,则每次运行函数组件都会调用该方法
//如果使用了依赖项,则第一次调用后,会进行缓存,只有依赖项发生变化时才会重新调用函数
useImperativeHandle(ref,() => {
return {
method(){
console.log("Test Component Called")
}
}
}, [])
return <h1>Test Component</h1>
}
// 转发
const TestWrapper = React.forwardRef(Test)
export default function App() {
const testRef = useRef();
return (
<div>
<TestWrapper ref={testRef} />
<button onClick={() => {
testRef.current.method();
}}>点击调用Test组件的method方法</button>
</div>
)
}
博主开始运营自己的公众号啦,感兴趣的可以关注“飞羽逐星”微信公众号哦,拿起手机就能阅读感兴趣的博客啦!