React ref returns a 'Connect' object instead of DOM

后端 未结 2 484
攒了一身酷
攒了一身酷 2020-12-31 11:38

I\'m trying to create dynamics refs for custom components created through the map function.

相关标签:
2条回答
  • 2020-12-31 12:21

    It seems like Post is a connected component, while you actually want the wrapped one.

    react-redux ≥ 6.0.0

    Connect with forwardRef: true

    connect(null, null, null, { forwardRef: true })(Post);
    

    then add a ref normally:

    ref={ref => this.<id> = ref}
    

    From the docs:

    If {forwardRef : true} has been passed to connect, adding a ref to the connected wrapper component will actually return the instance of the wrapped component.




    react-redux < 6

    Connect with withRef: true

    connect(null, null, null, { withRef: true })(Post);
    

    then use getWrappedInstance() to get the underlying connected component:

    this.refs[<id>].getWrappedInstance()
    

    From the docs:

    [withRef] (Boolean): If true, stores a ref to the wrapped component instance and makes it available via getWrappedInstance() method. Default value: false

    0 讨论(0)
  • 2020-12-31 12:21

    An alternative way to do this would be to use some other prop name (other than ref). For example:

    <Post
      ...
      innerRef={(node) => { this.myRef = node; }}
    />
    

    This also works if you're using a library like styled-components or emotion

    0 讨论(0)
提交回复
热议问题