【问题标题】:Using ref into class and hook在类中使用 ref 和钩子
【发布时间】:2023-01-30 06:01:44
【问题描述】:

几年前写的一类react代码。

它的代码使用 ref,调用另一个组件函数。

像这样。

源码

class Login extends React.Component {
  processWindow = null;

  someFunction = () => {
    this.processWindow
  }

  render() {
    <ProgressWindow
       ref={ref => {
         this.processWindow = ref;
       }}
    />

其作品。

但是把class组件改成function组件后就开始麻烦了。

另一个组件转换为功能组件,没有在原始组件中找到任何引用。

我如何向另一个组件添加一些代码?

来自类组件的 console.log(ref)

来自函数组件的 console.log(ref) 无效的

【问题讨论】:

  • “但是把class组件改成function组件后就麻烦了。”代码在哪里?你能提供可重现的例子吗?
  • 另一个组件是类,有效。但是,另一个组件转换为功能组件,任何东西都在原始组件中找到引用。将类转换为函数后问题开始。
  • 你试试forwardRef

标签: reactjs react-hooks


【解决方案1】:

这有帮助吗

import { useRef } from 'react';

function Login(props) {
  const processWindowRef = useRef();

  return (
    <ProgressWindow
      ref={ref => { processWindowRef.current = ref; }}
      // can try 
      // ref={processWindowRef}
     />
  );
});

Beta 文档中有关 useRef 的更多信息

希望能帮助到你

【讨论】:

  • 我知道最好的方法是将 login.js 转换为函数组件。但我无法转换。唯一的方法是隐藏另一个组件。
猜你喜欢
  • 1970-01-01
  • 2021-05-09
  • 2020-08-15
  • 2020-12-11
  • 1970-01-01
  • 2021-05-14
  • 2023-03-26
  • 1970-01-01
  • 2017-04-07
相关资源
最近更新 更多