2017-01-09 86 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

相關問題