|
forwardRef是React中的一个高级组件 ,主要用于实现 ref转发 或 透传[/p][p]即,将父组件的ref对象,传到子组件中,这样子组件与父组件都可以控制ref对象;
代码如下: 父组件: 如下代码中,定义的ref对象childRef , 将通过ref 属性,传给子组件 export function HookUseIh(props){
const childRef =useRef(null) // 定义的ref对象
const change =()=>{
childRef.current.focus();
}
return (
<div>
{/* 通过ref 属性,传给子组件 */}
<IHChild ref={childRef} />
<button onclick={change}>父组件中focus</button></div>
);
}子组件 : 第二个参数inputRef ,即是父组件中传递过来的ref对象,子组件可直接使用 export React.forwardRef(IHChild(props,inputRef)=>
// inputRef即是父组件中传递过来的ref对象,子组件可直接使用
const onChange=()=>{
inputRef.current.focus();
}
return (<div>
子组件
<input ref={inputRef} type="text"/>
<button onclick={onChange}>change</button></div>
)
} |
|
|