简体   繁体   English

如何在 react/react-native 中获取功能组件的节点处理程序

[英]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) .例如,在 react-native 中,如果在获取类组件的节点处理程序时,可以执行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 .功能组件没有实例,也没有自己的引用,但是,可以使用forwardRefsuseImperativeHandle使其可引用。 So, I'm looking for something similar to this for functional components.所以,我正在为功能组件寻找与this似的东西。 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我尝试使用从forwardRefs获得的引用,但它不起作用 - 它引发以下错误: 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.考虑改用 Class 组件。 Functional components does have instances功能组件确实有实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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