父组件
const pchildref:any = useRef();
const setImmediate = (num: number) => {
changeScope({...Object.assign(obj, {init:num})})
}
function handlerClick(){
console.log(pchildref.current._childFn())
}
return (
<>
<div className="title" onClick={handlerClick}>{obj.start}到{obj.end}</div>
<Boxs ref={pchildref} init={init}></Boxs>
</>
)
子组件
import React, { useImperativeHandle, useRef, forwardRef } from "react"
const Boxs = (props: { init: React.ReactNode; }, ref:any) => {
const childRef = useRef()
useImperativeHandle(ref, () => {
return {
_childFn() {
return "父组件 调用 子组件"
// something….
}
}
})
return (
<div ref={childRef} className="box">{props.init}</div>
)
}
export default forwardRef(Boxs)
报错信息:
ref={childRef}
Type 'undefined' is not assignable to type 'HTMLDivElement | null' TS2322
在线等
ref属性是react内置属性,不会作为props传给子元素。你可以换个名字wrapRef: