【问题标题】:ReactJS Can not get a Ref to a Class Component using ref callbackReactJS 无法使用 ref 回调获取类组件的 Ref
【发布时间】:2020-08-28 15:36:44
【问题描述】:

我正在尝试从父组件获取子组件(类组件)的引用,我遇到了两个问题:

Parent component

private childRef: RefObject<any> = React.createRef();

<Child ref={this.childRef} />

  1. ref 回调不会触发并在我的参考中得到一个空的{current: null}

  2. React-dev-tools 警告我从功能组件传递 ref,但我的子组件是类组件..

react_devtools_backend.js:2273 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

谁能帮忙?

仅供参考 在将我的应用程序从 PReact 迁移到 React 时出现此问题。 在 Preact 中,用于正确传递的 ref:

父母

 <Child ref={(ref: any) => {
                      if (ref && ref._component) {
                        this.childRef = ref._component._component
                      }
                    }}
</Child>

【问题讨论】:

  • 孩子长什么样子?
  • @Yatrix Child 组件是一个类组件:`class Child extends React.Component {} `

标签: reactjs preact react-ref


【解决方案1】:

你必须转发参考。

const Child = React.forwardRef((props, ref) => (
  <div ref={ref} >
    ....
  </div>
))

ref 不会自动从功能组件传递到它的 DOM 元素。所以你必须手动传递它。更多详情https://reactjs.org/docs/forwarding-refs.html

【讨论】:

    【解决方案2】:

    将其包裹在 div 中。试试这个:

    Parent component
    
    private childRef: RefObject<any> = React.createRef();
    
    <div ref={this.childRef} >
    <Child />
    <div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 2018-09-10
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2022-12-09
      相关资源
      最近更新 更多