React ref returns 一个 'Connect' 对象而不是 DOM
React ref returns a 'Connect' object instead of DOM
我正在尝试为通过地图函数创建的自定义组件创建动态引用。
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
returns refs.test
的正确 DOM 节点,但对于循环中的节点,它返回一个 Connect
对象。
有人能给我指出正确的方向吗?
看起来 Post
是一个连接组件,而您实际上想要的是包装组件。
react-redux ≥ 6.0.0
联系forwardRef: true
connect(null, null, null, { forwardRef: true })(Post);
然后正常加一个ref:
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
另一种方法是使用其他道具名称(ref
除外)。例如:
<Post
...
innerRef={(node) => { this.myRef = node; }}
/>
如果您使用 styled-components
或 emotion
这样的库,这也适用
我正在尝试为通过地图函数创建的自定义组件创建动态引用。
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
returns refs.test
的正确 DOM 节点,但对于循环中的节点,它返回一个 Connect
对象。
有人能给我指出正确的方向吗?
看起来 Post
是一个连接组件,而您实际上想要的是包装组件。
react-redux ≥ 6.0.0
联系forwardRef: true
connect(null, null, null, { forwardRef: true })(Post);
然后正常加一个ref:
ref={ref => this.<id> = ref}
来自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
联系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
另一种方法是使用其他道具名称(ref
除外)。例如:
<Post
...
innerRef={(node) => { this.myRef = node; }}
/>
如果您使用 styled-components
或 emotion