gpt4 book ai didi

reactjs - React ref 返回一个 'Connect' 对象而不是 DOM

转载 作者:行者123 更新时间:2023-12-03 13:20:59 27 4
gpt4 key购买 nike

我正在尝试为通过 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 对象。 Screenshot

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

最佳答案

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

<强> react-redux ≥ 6.0.0

联系forwardRef: true

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

然后正常添加引用:

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

来自docs :

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

联系withRef: true

connect(null, 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

关于reactjs - React ref 返回一个 'Connect' 对象而不是 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41554365/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com