首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在function函数类上调用函数?

如何在function函数类上调用函数?
EN

Stack Overflow用户
提问于 2021-02-20 17:33:05
回答 1查看 130关注 0票数 0

我想通过访问useRef.current来调用类上的函数,就像使用类组件和DOM对象一样。我知道关于DOM和类实例等的所有规则,这使得useRefs成为可能,但是如何调用myfunctioncomponent.method()呢?

沙箱显示了错误:

https://codesandbox.io/s/class-vs-function-useref-zjee5?file=/src/App.js

错误:

警告:不能给函数组件参考。访问此引用的尝试将失败。您是想使用React.forwardRef()吗?

代码:

代码语言:javascript
复制
export const App = () => {
  let functionref = useRef(null);
  let domref = useRef(null)
  let classref = useRef(null);

  useEffect(() => {
    console.log(functionref); // fails :(
    console.log(domref); // works! 
    console.log(classref); // works !
    classref.current.callme(); // works!
    classref.current.callme(); // fails!
  }, []);
  return (
    <>
      <ClassComponent ref={classref}/>
      <div ref={domref}>This is a DOM node</div>
      <FunctionComponent ref={functionref} />
    </>
  );
};

class ClassComponent extends React.Component {
  callme() {
    console.log("ClassComponent function called!");
  }
  render() {
    return (
      <p>This is a class component</p>
     )
  }
}

const FunctionComponent = () => {
  const callme = () => {
    console.log("function called!");
  }

  return (
   <p>This is a function component</p>
  )
}

也许我是想过分扭曲规则,或者引入反模式(?)如果是这样的话,我非常感谢关于访问函数组件或其他组件中的函数和属性的正确方法的建议。

任何帮助都很感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-20 18:27:41

对于您想要做的事情,您需要使用一个forwardRef,以便将ref传递给functional,我在下面给出了一个示例片段。在类组件中,ref允许您访问类组件方法,但是当您使用未发生的反应性功能组件进行访问时。相反,你只需拿回裁判,就由你来决定裁判中会有什么。这就是为什么在下面的代码片段中,您需要添加ref.current = { callme },以便callme方法在被调用为functionref.current.callme()时可用。

代码语言:javascript
复制
const FunctionComponent = React.forwardRef((_props, ref) => {
  const callme = () => {
    console.log("function called!");
  };

  ref.current = { callme };

  return <p>This is a function component</p>;
});

这是一个那个密码箱

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66294583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档