代码之家  ›  专栏  ›  技术社区  ›  MakePeaceGreatAgain

不能在函数组件中使用ref

  •  0
  • MakePeaceGreatAgain  · 技术社区  · 11 月前

    我正试图在react中获取父对象中的子对象组件的宽度:

    import { FC, PropsWithChildren, useRef } from "react";
    
    const MyParent: FC<PropsWithChildren> = (props) => {
        const myref = useRef(null);
        return (<MyChild ref={myref}/>)
    }
    
    const MyChild: FC<PropsWithChildren> = (props) => {
        return (<View />)
    }
    

    然而,这不会编译。我得到以下错误:

    类型“{ref:MutableRefObject;}”不可分配给类型 '本质属性&{children?:ReactNode;}'。属性“ref” 在类型'IntrinsicAttributes&{children?:ReactNode; }'.ts(2322)

    我以为每个对象都可以用作引用。我怎么能对我的孩子使用引用呢?

    2 回复  |  直到 11 月前
        1
  •  0
  •   Arash jahan bakhshan    11 月前

    那是因为 ref 是react中保留的道具,不能直接指定为道具。但你可以使用 forwardRef 这样做的功能:

    import {type PropsWithChildren, forwardRef} from "react";
    
    const MyChild = forwardRef<View, PropsWithChildren>((props, ref) => {
        return <View ref={ref} />
    })
    
    MyChild.displayName = "MyChild";
    
    const MyParent: FC<PropsWithChildren> = (props) => {
        const myref = useRef<View>(null);
    
        return (<MyChild ref={myref}/>)
    }
    

    您可以在官方文档中阅读更多信息( https://react.dev/reference/react/forwardRef )

        2
  •  0
  •   Nickofthyme    11 月前

    您需要使用 forwardRef 作用请参阅下面的示例。。。

    import { FC, PropsWithChildren, useRef, forwardRef } from "react";
    
    const MyParent: FC<PropsWithChildren> = (props) => {
        const myref = useRef(null);
        return (<MyChild ref={myref}/>)
    }
    
    const MyChild: FC<PropsWithChildren> = (props) => {
        return <div />
    }
    
    const MyInput = forwardRef<<HTMLDivElement, PropsWithChildren>>(function MyInput(props, ref) {
        return <div />
    });