简体   繁体   中英

How to get the node handler of a functional component in react/react-native

For example, in react-native, if when getting the node handler of a class component, one can do ReactNative.findNodeHandler(this) . Functional components don't have instances and they don't hold their own refs but, one could make it referencable using forwardRefs and useImperativeHandle . So, I'm looking for something similar to this for functional components. I've tried using its reference obtained from forwardRefs but it's not working - It throws the following error: Error: Argument appears to not be a ReactComponent. Keys: current Error: Argument appears to not be a ReactComponent. Keys: current

below is how I'm trying to use it:

 export const NativeComponent = forwardRef(
  (
    { onChange }: PropsType,
    ref: ForwardedRef<BaseRef>
  ) => {
    const makeNativeCommandRequest = (name: string, params: Array<any>) => {
      UIManager.dispatchViewManagerCommand(
        findNodeHandle(ref as unknown as number),
        UIManager.getViewManagerConfig("NativeComponent").Commands[name],
        params
      );
    };
    useImperativeHandle(ref, () => ({
      command1() {
        makeNativeCommandRequest("command2", []);
      },
      command2() {
        makeNativeCommandRequest("command1", []);
      },
    }))});

Consider using Class components instead. Functional components does have instances

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM