2016-05-13 18 views
-1

コンポーネントのES6クラスを使用してReactjsでアプリケーションを作成しています。 引数を持つクラスの中で関数を呼び出すまで、コードは意図したとおりに動作します。ES6クラスの引数を持つ関数を呼び出す方法は?

SampleClass.js

class SampleClass extends React.Component { 
    constructor(props, context) { 
     super(props, context); 
     this.state = { 
     backgroundColor: 'yellow' 
     } 
    } 

    onChangeBackgroundColor(backgroundColor) { 
     this.setState({ 
     backgroundColor: backgroundColor 
     }) 
    } 

    render() { 
     return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}> 
     <span onClick={this.onChangeBackgroundColor.bind(this)} style={{background: 'white'}}> 
      Change element style 
     </span> 
     </div> 
    } 
} 

React.render(<SampleClass />, document.getElementById('container')); 

私はthis.onChangeBackgroundColor.bind(this)のような引数なしの関数の罰金を呼び出すことができています。

しかし、関数に引数を渡すと、コンソールでエラーが発生します。 Uncaught TypeError: Cannot read property 'bind' of undefined

参考フィドル:https://jsfiddle.net/purezen/s6ap3m8s/3/

+0

をあなたは、引数を含めている例を共有していただけますか? –

答えて

2
this.onChangeBackgroundColor.bind(this, arg1, arg2) 

あなたがそれらを関数にバインドしたい場合はあなたの引数は、this後、バインド・コールに行く必要があります。

@ivarniは述べたとドキュメントを反応させるのあたりに、それはコンストラクタで結合するのに最善であるように、「我々は、彼らが唯一の結合しているので、あなたは、コンストラクタであなたのイベントハンドラをバインドすることをお勧めしますより多くの情報

については、以下のリンクを参照してください一度すべてのインスタンスに対して:」

https://facebook.github.io/react/docs/reusable-components.html

+1

'constructor'で関数をバインドする必要があります。 'render'でそれらを束縛することは、コンポーネントをレンダリングするたびにバインドする必要があることを意味します。 – ivarni

+0

あなたは正しいです、私はそれを私の答えに加えます。 – sheeldotme

0

私はred値を渡し、あなたのフィドルを編集し、それが動作します。

あなたは彼らとES6のラムダ() =>を使用しているあなたはbind機能

0

渡されたパラメータで、この値を修正するために結合クリックで対処するより良い方法に引数を渡す必要があり、それをhere

を見ることができます字句この正しい値のバインド:

render() { 
    return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}> 
    <span onClick={() => this.onChangeBackgroundColor(arg1, arg2)} style={{background: 'white'}}> 
     Change element style 
    </span> 
    </div> 
} 
関連する問題