最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does React not explicitly export forwardRef? - Stack Overflow

programmeradmin3浏览0评论

UPDATE: There is nothing wrong with the implementation below. The error was due to a react-redux upgrade, as redux now relies on functional ponents instead of class ponents.

import React, { forwardRef } from 'react'

const DivWithRef = forwardRef((props, ref) => {
  return(
    <div ref={ref} {...props}>
      {props.children}
    </div>
  )
})
class AClassComponent extends Component {
  render() {
    return (
      <DivWithRef ref={me => this.node = me} />
    ) 
  }
}

When I try this I get the error:

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

Does react not explicitly export forwardRef?

I have been using this code for a while, and it never caused any issues. After I updated to React 16.8, I started getting the warning above, but my app can still access the DOM Ref even though react claims it shouldn't be able to.

UPDATE: There is nothing wrong with the implementation below. The error was due to a react-redux upgrade, as redux now relies on functional ponents instead of class ponents.

import React, { forwardRef } from 'react'

const DivWithRef = forwardRef((props, ref) => {
  return(
    <div ref={ref} {...props}>
      {props.children}
    </div>
  )
})
class AClassComponent extends Component {
  render() {
    return (
      <DivWithRef ref={me => this.node = me} />
    ) 
  }
}

When I try this I get the error:

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

Does react not explicitly export forwardRef?

I have been using this code for a while, and it never caused any issues. After I updated to React 16.8, I started getting the warning above, but my app can still access the DOM Ref even though react claims it shouldn't be able to.

Share Improve this question edited May 21, 2019 at 18:38 Jeremy Gottfried asked May 20, 2019 at 22:00 Jeremy GottfriedJeremy Gottfried 1,20116 silver badges32 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You want to do this instead:

constructor() {
  this.node = React.createRef();
}
// more code
render() {
  return <DivWithRef ref={this.node} />;
}

The rest of your code is correct.

I answered it on my own. It's not a problem with my implementation. Callback refs are a valid implementation, as explained here: reactjs/docs/refs-and-the-dom.html#callback-refs

The reason for the error is that the latest version of react-redux uses functional ponents instead of class ponents. After I updated to react-redux, my refs on connected ponents return the error.

The second ref argument only exists when you define a ponent with React.forwardRef call.

React.forwardRef

发布评论

评论列表(0)

  1. 暂无评论