2016-09-22 1 views
0

以下のコードでは、子QRScanコンポーネントに渡される小道具closeModal子コンポーネント内の関数で呼び出すことができるように、小道具を介して子コンポーネントに渡された関数にバインドするにはどうすればいいですか?

私はQRScanのコンストラクタでthis.props.closeModal.bind(this)を試みたが、私は_onBarCodeRead機能でthis.props.closeModal()を呼び出すとき、私はundefined is not an object (evaluating 'this.props.closedModal')エラーを取得します。

小道具が間違いなくコンストラクタに渡されているため、関数を正しくバインドできないようです。どんな助けも大変ありがとう!

class Test extends React.Component { 

constructor(props) { 
    super(props); 
} 

_test(){ 
    console.log("test worked") 
} 

render() { 
    return (
    <View> 
     <QRScan closeModal={this._test}/> 
    </View> 
    } 
} 

子クラス:インプレース機能を変更しない機能をバインド

class QRScan extends React.Component { 

constructor(props) 
{ 
super(props) 
console.log(this.props) 
this.props.closeModal.bind(this); 
} 

render() { 
    return (
    <BarcodeScanner 
     onBarCodeRead={this._onBarCodeRead} 
     width={windowWidth} 
     height={windowWidth * cameraAspectRatio} 
     style={styles.camera}> 
     <View style={styles.rectangleContainer}> 
     <View style={styles.rectangle} /> 
     </View> 
    </BarcodeScanner> 
); 
} 
_onBarCodeRead(e) { 
    console.log(e); 
    Vibration.vibrate(); 
    this.props.closeModal(); 
    } 
} 

答えて

0

問題は実際にはthis._onBarCodeReadが正しくバインドされていないことです。子コンポーネントのコンストラクタで

は、あなたの答えは、多くのおかげで非常に単純なときに私はそれを嫌う this._onBarCodeRead = this._onBarCodeRead.bind(this);

+0

以下を追加する必要があります! –

0

。代わりに、変数に代入できる結果の関数を返します。

だから理論的にはthis.props.closeModal = this.props.closeModal.bind(this);とすることができますが、それは反応しないでしょう。だから代わりに、私はクラスのメソッドを作成し、それをバインドし、そこから小道具にアクセスすることをお勧めします。たとえば、次のように

もちろん
class QRScan extends React.Component { 

    constructor(props) 
    { 
    super(props) 
    this.closeModal = this.closeModal.bind(this) 
    } 
    closeModal() { 
    this.props.closeModal.call(this); 
    } 
} 

、あなたの小道具のメソッドに渡すのではなく、クラス内thisを維持助言する物事の一般的推奨される方法。

コードを機能させるには、this._onBarCodeReadメソッドで同じバインディングを行う必要があると思います。

関連する問題