React ref返回一个“ Connect”对象而不是DOM
我正在尝试为通过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对象。

有人可以指出我正确的方向吗?
回答:
似乎Post是一个连接的组件,而您实际上需要包装的组件。
与连接 forwardRef: true
connect(null, null, null, { forwardRef: true })(Post);然后通常添加一个引用:
ref={ref => this.<id> = ref}从文档:
如果
{forwardRef : true}已传递给connect,则向连接的包装器组件添加一个ref实际上将返回被包装组件的实例。
与连接 withRef: true
connect(null, null, null, { withRef: true })(Post);然后用于getWrappedInstance()获取基础的连接组件:
this.refs[<id>].getWrappedInstance()从文档:
[withRef](布尔值):如果为true,则将ref存储到包装的组件实例,并通过
getWrappedInstance()method使其可用。默认值:
false
以上是 React ref返回一个“ Connect”对象而不是DOM 的全部内容, 来源链接: utcz.com/qa/409628.html
