【问题标题】:How can i call a function on a React functional class?我如何在 React 函数类上调用函数?
【发布时间】:2021-05-23 10:46:21
【问题描述】:

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

沙盒演示错误:

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

错误:

警告:函数组件不能被赋予 refs。尝试访问此 ref 将失败。你的意思是使用 React.forwardRef() 吗?

代码:

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>
  )
}

也许我试图过多地改变规则或引入反模式(?)如果是这样,我非常感谢有关访问功能组件内的函数和属性的正确方法或替代方案的建议。

任何帮助表示赞赏。

【问题讨论】:

  • 在 React 文档中检查 forwardRef
  • 如警告所示,您不能将 ref 附加到函数组件。使用forwardRef,您可以转发 ref(在这种情况下,转发到底层&lt;p&gt; 元素)。如果你想要一个有公共方法的组件,你需要使用一个类组件。
  • 不一定如此。可以通过功能组件来实现。见下文。

标签: reactjs react-functional-component use-ref


【解决方案1】:

对于您要执行的操作,您需要使用 forwardRef 以便将 ref 传递给功能组件,我在下面放置了一个示例 sn-p。在类组件中,引用允许您访问类组件方法,但是当您使用不会发生的反应功能组件时这样做。相反,您只需取回 ref 并由您来决定 ref 中的内容。这就是为什么在下面的 sn-p 中您需要添加 ref.current = { callme } 以便 callme 方法在以 functionref.current.callme() 调用时可用。

const FunctionComponent = React.forwardRef((_props, ref) => {
  const callme = () => {
    console.log("function called!");
  };

  ref.current = { callme };

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

这是codesandbox of that

【讨论】:

  • 这就是解决方案。谢谢你的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 2020-07-04
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
相关资源
最近更新 更多