问题
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?
回答1:
It seems like Post is a connected component, while you actually want the wrapped one.
You'll have to 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
回答2:
An alternative way to do this would be to use some other prop name (other than ref). For example:
<Post
...
innerRef={(node) => { this.myRef = node; }}
/>
This also works if you're using a library like styled-components or emotion
来源:https://stackoverflow.com/questions/41554365/react-ref-returns-a-connect-object-instead-of-dom