加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React ref返回一个’Connect’对象而不是DOM

发布时间:2020-12-15 05:06:45 所属栏目:百科 来源:网络整理
导读:我正在尝试为通过map函数创建的自定义组件创建动态参考. class PostsList extends Component { constructor(props) { super(props); } componentDidUpdate = () = { console.log(this.refs); } render() { let posts = this.props.posts || []; return ( div
我正在尝试为通过map函数创建的自定义组件创建动态参考.
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

console.log为refs.test返回正确的DOM节点,但对于循环中的节点,它返回一个Connect对象.

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

看起来Post是一个连接组件,而你实际上想要包装它.

你必须用withRef连接:true:

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

然后使用getWrappedInstance()来获取底层连接组件:

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

从docs:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读