3

Lets say I have some component wo which I pass a function.

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

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

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

OR

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

        )
    }
}

Where is the difference between onLayout={this._someFunc()} and onLayout={() => {this._someFunc()}}?

3
  • Did you mean difference between onLayout={this._someFunc} and onLayout={() => {this._someFunc()}}? Commented Sep 13, 2017 at 8:11
  • @bennygenel exactly. As I stated in the last sentence of the Q. Commented Sep 13, 2017 at 8:12
  • No. You didn't. First of all there is a difference between onLayout={this._someFunc()} and onLayout={this._someFunc}. Commented Sep 13, 2017 at 8:15

1 Answer 1

2

The difference depends really how and when onLayout is triggered.

  • onLayout={this._someFunc()}

    Each time your component is rendered the onLayout prop will get the return value from the this._someFunc() function. In other words, the function will run on every render.

  • onLayout={() => {return this._someFunc()}} or onLayout={() => this._someFunc()}

    Each time your component is rendered the onLayout prop will bind the reference to an anonymous function which contains the call to the _someFunc() function. The latter function doesn't get executed unless onLayout is somehow triggered.


For example, assume the following component:

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>

In component A the foo prop will get the value of "bar".

In component B the foo prop will be a reference to a function that you can later call. That function will in turn call _someFunc which will return "bar". So if in component B you want to get the value, you need to call it with this.props.foo().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.