React ref返回一个“ Connect”对象而不是DOM [英] React ref returns a 'Connect' object instead of DOM

查看:156
本文介绍了React ref返回一个“ Connect”对象而不是DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为通过map函数创建的自定义组件创建动态引用。

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

class PostsList extends Component {

  constructor(props) {
    super(props);
  }

  componentDidUpdate = () => {
    console.log(this.refs);
  }

  render() {
    let posts = this.props.posts || [];
    return (
        <div ref="test">
          {posts.map((post) => {
            return <Post post={post} key={post.id} ref={post.id}></Post>
          })}
        </div>
    );
  }

}

export default PostsList

控制台.log 返回 refs.test 的正确DOM节点,但对于循环中的节点,它返回 Connect 对象。

the console.log returns the correct DOM node for refs.test but for the ones in the loop, it's returning a Connect Object.

有人可以指出我正确的方向吗?

Can someone point me in the right direction?

推荐答案

Post 似乎是一个连接的组件,而实际上您需要包装的组件。


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

react-redux≥6.0.0

react-redux ≥ 6.0.0

使用 forwardRef:true

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

然后通常添加引用:

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

来自文档


如果 {forwardRef:true} 已传递给 connect ,则将引用添加到
连接的包装器组件实际上将返回
包装的组件的实例。

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




react-redux < 6

连接 withRef:true

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

然后使用 getWrappedInstance()获取基础连接组件:

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

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

来自文档


[withRef](布尔值):如果为true,则将引用存储到包装的组件实例,并通过 getWrappedInstance()方法使其可用。默认值: false

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

这篇关于React ref返回一个“ Connect”对象而不是DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆