React ref 返回一个“Connect”对象而不是 DOM

IT技术 reactjs dom redux react-redux
2021-05-21 07:52:29

我正在尝试为通过 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返回正确的DOM节点refs.test,但在循环的那些,它返回一个Connect对象。 截屏

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

2个回答

看起来像是Post一个连接的组件,而你实际上想要一个包裹的组件。

react-redux ≥ 6.0.0

与连接 forwardRef: true

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

然后正常添加一个引用:

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

文档

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




react-redux < 6

与连接 withRef: true

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

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

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

文档

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

另一种方法是使用其他一些props名称(除了ref)。例如:

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

如果您使用的是像styled-components这样的库,这也适用emotion