1.forwardRef的使用
javascript
import { forwardRef, useRef } from "react"
const Son = forwardRef((props, ref)=> {
return (
<input type="text" ref={ref} id="kannoId"/>
)
})
function ForwardRef() {
const sonRef = useRef(null)
const showRef = () => {
console.log("sonRef", sonRef.current,document.getElementById('kannoId'));
sonRef.current.focus()
// document.getElementById('kannoId').focus()
}
return (
<div>
我是父组件
<button onClick={showRef}>点击</button>
<Son ref={sonRef} />
</div>
)
}
export default ForwardRef
说明:获取子组件中的节点可以通过子传父、js获取节点方式、forwardRef
2.useImperativeHandle的使用
javascript
import { forwardRef, useRef,useImperativeHandle } from "react"
const Son = forwardRef((props, ref)=> {
function kanno(){
console.log("36除了6还是6");
}
useImperativeHandle(ref,()=>{ // 使用钩子函数暴露子组件中的方法
return {
kanno
}
})
return (
<input type="text" id="kannoId"/>
)
})
function ForwardRef() {
const sonRef = useRef(null)
const showRef = () => {
console.log("sonRef", sonRef.current,document.getElementById('kannoId'));
sonRef.current.kanno()
// sonRef.current.focus()
// document.getElementById('kannoId').focus()
}
return (
<div>
我是父组件
<button onClick={showRef}>点击</button>
<Son ref={sonRef} />
</div>
)
}
export default ForwardRef