2016-12-23 10 views
0

私はおそらく間違った質問をしていますが、イベントではなく子関数から呼び出されたときに親関数を実行できるようにしたいと考えています。Reactでイベントハンドラの外部でバインドされた関数を実行するには?

私は、親で_fooメソッドを宣言し、それをonClickイベントハンドラを介して実行するChildTwoに渡すと、期待どおりに動作します。しかし、別のメソッドの内部から_fooメソッドを手動で呼び出す必要がある状況に遭遇しました(私はここで単純化しましたが、条件付きで呼び出されます)。

私の質問は、_bar(_)から_fooメソッドを呼び出すために何をする必要がありますか?

ありがとうございます!あなたが本当にこれをしたい場合は

export defaultclass Parent extends Component { 
 
    constructor() { 
 
    super(); 
 
    } 
 

 
    _foo() { 
 
    alert('alert!'); 
 
    } 
 

 
    render() { <ChildOne _foo={this._foo.bind(this)} /> } 
 
} 
 

 
const ChildOne = (props) => { 
 
    const { _foo } = props; 
 
    return (<ChildTwo _foo={_foo} />); 
 
} 
 

 
export default class ChildTwo extends Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this._foo = this.props._foo.bind(this); 
 
    } 
 

 
    _bar() { 
 
    //this._foo.call(); 
 
    //this._foo(); 
 
    //what do I do here? 
 
    } 
 

 
    render() { 
 
     return (
 
     <div> 
 
      <button onClick={this._foo}> Works! </button> 
 
      <button onClick={this._bar}>Doesnt Work!</button> 
 
     </div> 
 
    ); 
 
    } 
 
};

+0

: '<ボタンのonClick = {} this._foo>作品! 'あるいは少なくとも' this._foo'は定義されていないので、少なくとも何もしてはいけません。私はそれが例では単にタイプミスであると仮定していますので、あなたのスニペットを再度チェックして元のコードと一致するかどうかを確認し、すべてのタイプミスを修正できますか? –

+0

@NikolajDamLarsenああ、ありがとう! 'Tisは修正されました。 – madhermit

+1

コンポーネント内の関数をコールバックとして使用する場合、コールバック関数をコンポーネントにバインドする必要があります。そうでなければ、関数本体で 'this'を使用すると間違ったオブジェクトを参照します。したがって、あなたの 'ChildTwo'コンポーネントでは、この行をコンストラクタに追加する必要があります:' this._bar = this._bar.bind(this) '。それから、 '_bar'の本体で' this._foo(); 'を呼び出すことができます。 –

答えて

1

、その後、私はまだ元の親にバインドされているメソッドの引数として子コンポーネントを渡すことによって、それを解決するだろう。例えば

:これは動作しないはずです

export defaultclass Parent extends Component { 
    constructor() { 
    super(); 
    this._foo = this._foo.bind(this) 
    } 

    _foo(childComponent) { 
    alert({ parent: this, child: childComponent }); 
    } 

    render() { <ChildOne _foo={this._foo} /> } 
} 

const ChildOne = (props) => { 
    const { _foo } = props; 
    return (<ChildTwo _foo={_foo} />); 
} 

export default class ChildTwo extends Component { 
    constructor(props) { 
    super(props); 
    this._bar = this._bar.bind(this); 
    } 

    _bar() { 
    const { _foo } = this.props; 

    // Passing a reference to self as argument 
    _foo(this); 
    } 

    render() { 
     return (
     <div> 
      <button onClick={this._bar}>Should Work Now!</button> 
     </div> 
    ); 
    } 
}; 
関連する問題