2017-09-13 8 views
3

私は関数を渡すいくつかのコンポーネントを持っていると言います。反応ネイティブでの関数の使用の違い

export default class SomeComp extends Component { 
    constructor(props) { 
     super(props); 
    } 

    _someFunc =() => { 
     return ... 
    } 

    render() { 
     return (
      <View 
       onLayout={this._someFunc()} 
      /> 

OR onLayout={this._someFunc()}onLayout={() => {this._someFunc()}}の違いがある

  <View 
       onLayout={() => {this._someFunc()}} 
      /> 

     ) 
    } 
} 

+0

あなたは 'onLayout = {this._someFunc}'と 'onLayout = {()=> {this._someFunc()}}'の違いを意味しましたか? – bennygenel

+0

@bennygenel。 Q:Q: – Stophface

+0

の最後の文で述べたように、あなたはそうしませんでした。まず、 'onLayout = {this._someFunc()}'と 'onLayout = {this._someFunc}'の違いがあります。 – bennygenel

答えて

2

実際はonLayoutがどのようにトリガされるかによって異なります。

  • onLayout={this._someFunc()}

    あなたのコンポーネントがonLayout小道具がthis._someFunc()関数からの戻り値を取得しますレンダリングされるたびに。つまり、関数はすべてのレンダリングで実行されます。

  • onLayout={() => {return this._someFunc()}}または

    コンポーネントがonLayout小道具が_someFunc()関数の呼び出しが含まれている匿名関数への参照をバインドするレンダリングされるたびにonLayout={() => this._someFunc()}。後者の関数は、onLayoutが何らかの形でトリガーされない限り実行されません。例えば


、次のコンポーネントと仮定:foo小道具は"bar"の値を取得するコンポーネントA

class MyApp extends React.Component { 
 

 
    _someFunc =() => { 
 
    return "bar"; 
 
    } 
 

 
    render() { 
 
    return(
 
     <div> 
 
     <A foo={this._someFunc()} /> 
 
     <B foo={() => {return this._someFunc()}} /> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
const A = ({foo}) => { 
 
    console.log(foo); //prints "bar" 
 
    return <div>A</div>; 
 
} 
 

 
const B = ({foo}) => { 
 
    console.log(foo); //prints the reference to _someFunc() 
 
    console.log(foo()); //prints "bar" 
 
    return <div>B</div>; 
 
} 
 

 
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

を。

コンポーネントBfoo小道具は、後で呼び出すことができる関数への参照になります。その関数は、"bar"を返す_someFuncを呼び出します。したがって、コンポーネントBで値を取得したい場合は、this.props.foo()で呼び出す必要があります。

+1

よく説明されています。ありがとう! – Stophface

関連する問題