2017-04-12 12 views
1

この問題は、コードスニペットのコメントに大まかにまとめられています。 this._setSizeconstructorにバインドすると、componentDidMountで呼び出されても、this.containerを知ることはできません。私は間違って何をしていますか?ありがとう!React ComponentDidMountでイベントリスナーを参照して取り付ける正しい方法はありますか?

export default class MyComponent extends React.Component { 
 
    constructor() { 
 
    super() 
 
    this._setSize = this._setSize.bind(this) 
 
    } 
 

 
    componentDidMount() { 
 
    const container = this.container // <div></div> :) 
 
    this._setSize() 
 
    window.addEventListener('resize', this._setSize) 
 
    } 
 

 
    componentWillUnmount() { 
 
    window.addEventListener('resize', this._setSize) 
 
    } 
 

 
    _setSize() { 
 
    const container = this.container // undefined :(
 
    const containerSize = { 
 
     x: container.offsetWidth, 
 
     y: container.offsetHeight 
 
    } 
 
    this.setState({ containerSize }) 
 
    } 
 

 
    render() { 
 
    return (
 
     <div ref={node => this.container = node}> 
 
     </div> 
 
    ) 
 
    } 
 
}

答えて

4

セットアップコンテナrefに機能の新しいインスタンスを作成して渡している各再レンダリング以内。前の関数はnullで呼び出されます。あなたがここにコンポーネントのインスタンスメソッドの代わりに、インライン関数を渡す

<div ref={node => this.container = node}> 

が、それはコンポーネントアンマウント中nullで参照し、二回目で一度呼び出されます。したがって、あなたが誤ってthis.containernullに設定されていることが起こるかもしれません。例:

// dont forget to bind it in constructor 
onContainerRef (node) { 
    // furthermore you can even check if node is not null 
    // if (node) { ... 
    this.container = node 
} 

// ... in render 
<div ref={this.onContainerRef}> 

詳しくはdocsをご覧ください。

1

私はあなたのコードを固定し、それが今働いている:see working DEMO

問題でしたか?

componentWillUnmount() { 
    window.addEventListener('resize', this._setSize) 
} 

componentWillUnmountにあなたがaddEventListener代わりのremoveEventListenerを持っているので、あなたはwindowからイベントリスナーを削除しませんでした。コンポーネントの条件付きレンダリングがある場合は、resizeイベント_setSizeにも呼び出されます。

は、この問題を説明壊れたデモで遊ぶと Toggleボタンをクリックし、出力を見て: see broken DEMO

関連する問題