2017-01-20 5 views
1
class HelloWorldComponent extends React.Component { 
    constructor() { 
    super() 
    this.getInput = this.getInput.bind(this) 
    } 
    getInput() { 
    alert('focused'); 
    } 
    render() { 
    return (  
     <input type="text" onFocus={getInput}/>  
    ); 
    } 
} 

ReactDOM.render(
    <HelloWorldComponent/>, 
    document.getElementById('react_example') 
); 

このコードで何が問題になっていますか?警告を発することができない、私はgetInputが定義されていないエラーを持っている。反応入力要素の "ReferenceError:getInputが定義されていません"

http://jsbin.com/qoduyawaci/1/edit

+1

'this.getInput = this.getInput.bind(この)' - なぜですか? –

+0

@ジャロマンダXなぜか? –

+0

私は間違っているかもしれませんが、 'this.getInput'はすでに' this'のプロパティであるため 'this'にバインドする必要はないと思っていたでしょう...私は私は99%が「これ」の仕組みを確信しているとしか言えませんが、ちょうど私に奇数(冗長)コードのように見えます –

答えて

4

あなたは正しいrefferenceを追加するのを忘れ。 this.getInput getInputの代わりにを使用してください。この

class HelloWorldComponent extends React.Component { 
    constructor() { 
    super() 
    this.getInput = this.getInput.bind(this); 
    } 
    getInput() { 
    alert('focused'); 
    } 
    render() { 
    return (  
     <input type="text" onFocus={this.getInput}/>  
    ); 
    } 
} 

ReactDOM.render(
    <HelloWorldComponent/>, 
    document.getElementById('react_example') 
); 
0

getInputのを使用する必要があります。 また、矢印 ES6で使用すると、バインディングを避けることができます。

getInput =() => { 
    alert('focused'); 
} 

、あなたは、コンストラクタで

this.getInput = this.getInput.bind(this) 

を回避することができます。これは正しいES6方法です。

http://jsbin.com/sebotirito/1/edit?html,js,output

+1

あなたの最初の提案は有効ではありませんES6。実験的な機能で、追加の設定が必要です。 –

+0

@FelixKling this.getInputは、クラスメンバー関数にアクセスするために使用されます。 – PranavPinarayi

+0

私は決して論争しなかった。たぶん私は自分自身をはっきりと表現していないかもしれない私は 'getInput =()=> ...'について話していました。 –

関連する問題