2017-01-09 85 views
4

我正在尝试为通过映射函数创建的自定义组件创建动态参考。React ref返回“连接”对象而不是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

refs.testconsole.log返回正确的DOM节点,但在循环的那些,它返回了Connect对象。 Screenshot

有人可以指出我在正确的方向吗?

回答

10

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

你必须与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

+0

在我的'Post.jsx'库这也适用,我接着说:出口默认连接(mapStateToProps,NULL,NULL,{withRefs :}}(Post);'当我尝试在我的PostList.jsx中调用'getWrappedInstance()'时,它会发出错误'错误:要访问包装的实例,您需要指定{withRef:true} connect()调用的选项参数。' 编辑:抱歉,我现在看到我的错误,应该是withRef,而不是withRefs –

0

替代这样做的方法是使用其他一些prop nam e(ref除外)。例如:

<Post 
    ... 
    innerRef={(node) => { this.myRef = node; }} 
/> 

如果你使用像styled-componentsemotion

相关问题