获取子组件dom和方法
[React19废弃] forwardRef 透传 父组件获取子组件的DOM
作用:允许组件使用ref将一个DOM节点暴露给父组件
import { forwardRef, useRef } from 'react'
const MyInput = forwardRef(function Input(props, ref) {
return <input {...props} type="text" ref={ref} />
}, [])
function App() {
const ref = useRef(null)
const focusHandle = () => {
console.log(ref.current.focus())
}
return (
<div>
<MyInput ref={ref} />
<button onClick={focusHandle}>focus</button>
</div>
)
}
export default App
29 useImperativeHandle 父组件 获取子组件的方法
作用:如果我们并不想暴露子组件中的DOM而是想暴露子组件内部的方法
import { forwardRef, useImperativeHandle, useRef } from 'react'
const MyInput = forwardRef(function Input(props, ref) {
// 实现内部的聚焦逻辑
const inputRef = useRef(null)
const focus = () => inputRef.current.focus()
// 暴露子组件内部的聚焦方法
useImperativeHandle(ref, () => {
return {
focus,
}
})
return <input {...props} ref={inputRef} type="text" />
})
function App() {
const ref = useRef(null)
const focusHandle = () => ref.current.focus()
return (
<div>
<MyInput ref={ref} />
<button onClick={focusHandle}>focus</button>
</div>
)
}
export default App
react19 允许组件使用 ref将 DOM 节点暴露给父组件
从 React 19 开始,你现在可以在函数组件中将
ref
作为 prop 进行访问:
新的函数组件将不再需要
forwardRef
,我们将发布一个 codemod 来自动更新你的组件以使用新的ref
prop。在未来的版本中,我们将弃用并移除forwardRef
。
function MyInput({placeholder, ref}) {
return <input placeholder={placeholder} ref={ref} />
}
//...
<MyInput ref={ref} />
获取方法
useImperativeHandle
是 React 中的一个 Hook,它能让你自定义由 ref 暴露出来的句柄。
在组件顶层通过调用
useImperativeHandle
来自定义 ref 暴露出来的句柄:
import { useImperativeHandle } from 'react';
function MyInput({ ref }) {
const add = (num1, num2) => {
return num1 + num2
}
useImperativeHandle(ref, () => {
return {
// ... 你的方法 ...
add
};
}, []);
// ...