React学习笔记20
一、React.forward
1.1、作用
通过ref暴露子组件的DOM
1.2、场景说明
1.3、语法实现
// 子组件
const Input = forwardRef((props,ref)=>{
return <input type="text" ref={ref} />
})
// 父组件
function father_component(){
const inputRef=useRef(null)
const focus=(ref)=>{
ref.current.focus()
}
return(
<>
<Input ref={inputRef}></Input>
<button onClick={()=>{focus(inputRef)}}></button>
</>
)
}
二、useInperativeHandle
1.1、作用
通过ref暴露子组件中的方法
1.2、场景说明
1.3、语法实现
// 子组件
const Input = forwardRef((props,ref)=>{
// 实现聚焦逻辑
const inputRef=useRef(null)
const focus_input=()=>{
inputRef.current.focus()
}
// 暴露聚焦方法
useImperativeHandle(ref,()=>{
return {
focus_input
}
})
return <input type="text" ref={inputRef} />
})
// 父组件
function father_component(){
const sonRef=useRef(null)
const focusHandle=(ref)=>{
}
return(
<>
<Input ref={sonRef}></Input>
<button onClick={()=>sonRef.current.focus_input()}></button>
</>
)
}
下一章:React学习笔记21:类组件