React ref 返回一个“Connect"对象而不是 DOM [英] React ref returns a 'Connect' object instead of DOM
问题描述
我正在尝试为通过 map 函数创建的自定义组件创建动态引用.
class PostsList extends Component {构造函数(道具){超级(道具);}componentDidUpdate = () =>{控制台日志(this.refs);}使成为() {让帖子 = this.props.posts ||[];返回 (<div ref="测试">{posts.map((post) => {return <Post post={post} key={post.id} ref={post.id}></Post>})}
);}}导出默认帖子列表
console.log
为 refs.test
返回正确的 DOM 节点,但对于循环中的那些,它返回一个 Connect
对象.
有人能指出我正确的方向吗?
看起来 Post
是一个连接的组件,而您实际上想要的是包装好的组件.
react-redux ≥ 6.0.0
连接forwardRef: true
connect(null, null, null, { forwardRef: true })(Post);
然后正常添加一个引用:
ref={ref =>这个= 参考}
来自 文档:
<块引用>如果 {forwardRef : true}
已传递给 connect
,则向连接的包装器组件实际上将返回包裹组件.
<人力资源>react-redux
6
连接withRef: true
connect(null, null, null, { withRef: true })(Post);
然后使用getWrappedInstance()
获取底层连接组件:
this.refs[].getWrappedInstance()
来自文档:
<块引用>[withRef](布尔值):如果为 true,则存储对包装组件实例的引用,并通过 getWrappedInstance()
方法使其可用.默认值:false
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
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?
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 toconnect
, 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
这篇关于React ref 返回一个“Connect"对象而不是 DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!