2017-01-09 11 views
4

私はmap関数で作成されたカスタムコンポーネントのダイナミクスリファレンスを作成しようとしています。React refはDOMの代わりに 'Connect'オブジェクトを返します

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.logrefs.testの正しいDOMノードを返しますが、ループ内のもののために、それはConnectオブジェクトを返します。 Screenshot

誰かが正しい方向に向かうことができますか?

答えて

10

Postは接続されたコンポーネントですが、実際にはラップされたものが必要です。

あなたはwithRef: trueに接続する必要があります:docsから

this.refs[<id>].getWrappedInstance() 

[withRef] (Boolean): If true, stores a ref to the wrapped component instance and makes it available via getWrappedInstance() method. Default value: false

+0

のようなライブラリを使用している場合、これがまた作品

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

、私は輸出のデフォルトは(mapStateToProps、NULL、NULL、{withRefsを接続'追加しました:Post}) 'PostList.jsxで' getWrappedInstance() 'を呼び出そうとすると、エラー' Error:ラップされたインスタンスにアクセスするには、{withRef:true}を指定する必要があります。 connect()呼び出しのoptions引数。 編集:申し訳ありませんが、私のエラーが表示され、withRefで、withRefsではないはずです –

0

代替

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

その後、基礎となる接続コンポーネントを取得するためにgetWrappedInstance()を使用しますこれを行う方法は、いくつかの他のプロップの名前を使用することですe(ref以外)。たとえば:あなたは私の `Post.jsx`でstyled-componentsまたはemotion

関連する問題