2016-12-29 3 views
0
class App extends React.Component { 
    method(){ 
     console.log(this); 
    } 
    render(){ 
     return (<div>   
      <button onClick={this.method}>Try it</button> 
     </div>) 
    } 
} 

ReactDOM.render(<App/>, document.getElementById('demo')); 

私はあなたがそれを持っている(これを)this.method.bind使用する必要がなぜ?なぜ起こるのボタン要素オブジェクトがundefined次のリアクションコードで、要素への参照が返されないのはなぜですか?

の代わりに返されている必要がありますので、ボタン要素は方法を駆動していると思います働いた?

+0

は、[どのように「このhttp://blog.andrewray.me/react-es6-autobinding-and-createclass/ –

+0

可能な複製を推奨読書します"関数内のキーワード作業?](http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-function) – aghidini

答えて

1

onClickに渡された関数が呼び出されたとき、クリックされたDOM要素のスコープで呼び出されます。thisはDOM要素です。 this参照を取得するには、参照をthisとして渡す新しい関数を作成する必要があります。ちょうどこれのための便利なメソッドがあります。bind。 あなたはそうのようにコンストラクタでバインドを設定することができます。

class App extends React.Component { 
    constructor (props) { 
     super(props); 
     this.method = this.method.bind(this); 
    } 
    method(){ 
     console.log(this); 
    } 
    render(){ 
     return (<div>   
      <button onClick={this.method}>Try it</button> 
     </div>) 
    } 
} 

ReactDOM.render(<App/>, document.getElementById('demo')); 
関連する問題