2016-10-16 11 views
0

私はthis methodを探していません。子ファンクから親関数をargなしで呼び出す方法

は、すべての引数を渡さずに親関数を呼び出す必要があります。

親(ES6):

foo(){ 
    ... 
    console.log("i was called"); 
} 

<Child callFoo={this.foo} /> 

子供(ES6):

// otherFunc() will be called by an onClick button event 
otherFunc(){ 
... 

this.props.callFoo; 
} 

上記は動作しません。これは動作しますが、私はこれを行う必要はありません。

親(ES6):

foo(bool){ 
    ... 
    if (bool){ 
    console.log("i was called"); 
    } 
} 

<Child callFoo={this.foo} /> 

は子供(ES6):

// otherFunc() will be called by an onClick button event 
otherFunc(){ 
... 

this.props.callFoo(true); 
} 

を簡単な呼び出しに方法はありますthis.props.callFooによる機能?

+0

this.props.callFoo();それは引数なしの関数を呼び出しています – Doppio

答えて

2

ブール値を渡す必要はありませんが、callFoo関数を実行するには括弧を使用する必要があります。ここにあなたの例を示します。

class Parent extends React.Component { 
 
    foo() { 
 
    console.log('i was called'); 
 
    } 
 
    render() { 
 
    return(
 
     <Child callFoo={this.foo}/> 
 
    ); 
 
    } 
 
} 
 

 
class Child extends React.Component { 
 
    otherFunc() { 
 
    this.props.callFoo(); 
 
    } 
 
    render() { 
 
    return(
 
     <div onClick={this.otherFunc.bind(this)}>Child</div> 
 
    ); 
 
    } 
 

 
} 
 

 
React.render(<Parent/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react-with-addons.min.js"></script> 
 
<div id="View"></div>

関連する問題