Reputation: 968
Suppose I had this layout below:
class Navigation extends React.Component {
primaryFun() { console.log('funn') }
secondaryFun() {
this.primaryFun();
}
}
I'd of expected this to then call primary but instead I get an undefined, Ok.
So I thought I'd add a constructor to bind the function to this:
constructor(props) {
super(props)
this.primaryFun = this.primaryFun.bind(this);
}
but primary fun is still undefined.
In my real project I'm calling these on a mouseOut event.
Feels like the above should work and tbh the documentation for React is all over the shot so couldn't find much here.
Upvotes: 7
Views: 54836
Reputation: 2032
You must bind() both two functions. You should that:
class Navigation extends React.Component {
constructor(props) {
super(props)
this.primaryFun = this.primaryFun.bind(this);
this.secondaryFun = this.secondaryFun.bind(this);
}
primaryFun() {
console.log('funn')
}
secondaryFun() {
this.primaryFun();
}
}
Upvotes: 0
Reputation: 1964
You need to bind this in your mouseOut
onMouseOut={this.secondaryFun.bind(this)}
Or a as best practice use the Lambda syntax. It'll bind this for you
onMouseOut={()=>this.secondaryFun()}
Upvotes: 2
Reputation: 81
Make sure both functions have the correct this
scope. If you are using class properties, see https://babeljs.io/docs/plugins/transform-class-properties/. Which already present on the babel-preset-react-app used by create-react-app, you can use that and write those as arrow functions, as seen on the babel link. And avoid having to use .bind
on the constructor.
Upvotes: 0
Reputation: 3433
Are you looking for something like this calling one function inside the other
import React, { Component } from 'react';
import './App.css'
class App extends Component {
constructor(){
super()
this.mouseClick = this.mouseClick.bind(this);
this.primaryFun = this.primaryFun.bind(this);
this.secondaryFun = this.secondaryFun.bind(this);
}
primaryFun(){
console.log('primaryFun funn')
}
secondaryFun(){
console.log('secondaryFun funn')
this.primaryFun()
}
mouseClick(){
this.secondaryFun()
}
render() {
return (
<div onClick={this.mouseClick}>
Hello World!
</div>
);
}
}
export default App;
Here when you click on "Hello world" secondaryFun is called and inside secondaryFun , primaryFun is been triggered
Upvotes: 5
Reputation: 2375
You also need to bind the secondaryFun
function to use this
inside that. Without that, the this
inside the function secondaryFun
will refers to the function scope which is secondaryFun
Upvotes: 2