无法从React上下文访问ref

问题描述 投票:0回答:1

出于某种原因,在 React 18 和 Typescript 5.x 中,我似乎无法访问通过上下文包装器明确设置和定义的 ref 的属性。我有这样的东西:

具有上下文的父组件


interface MyContextValues {
  ref: LegacyRef<ExternalApi>
} 

export const MyComponentContext = createContext<MyContextValues>({ref:null})

export const MyComponent = () => {
  const ref = useRef<ExternalThing | null>(null);

  useEffect(() => {
    console.log(ref.current); // ok!
  }, [ref]);

  return (
    <MyComponent.Provider> value={{ref}}
      <SomeComponent ref={ref}/>
    </MyComponent.Provider>);
}

export const useMyComponentContext<MyContextValues>(MyContext);

子组件

export const MyChildComponent = () => {
  const { ref } = useMyComponentContext();
  useEffect(() => {
    // Property 'current' does not exist on type 'string | ((instance: ExternalThing | null) => void) | RefObject<ExternalThing >'.
    // Property 'current' does not exist on type 'string'.ts(2339)

    console.log(ref.current);

    // But it actually logs out fine to the expected value... 
  }, [ref]);
  return <div></div>
}
reactjs
1个回答
0
投票

尝试用

React.RefObject
代替
React.LegacyRef

© www.soinside.com 2019 - 2024. All rights reserved.