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()}}?
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With