0

I've got a component like in the example

class ItemBox extends Component {

  constructor(props){
    super(props);
    this.someFn = this.someFn.bind(this);
  }

  someFn(){
    console.log(this)
  }

  render(){
    return (
      <div onClick={this.someFn}>bla<div/>
    )
  }
};

And i wanted to ask - is there some kind of a different solution for binding function to a component, except like i'm using in a constructor ( read it from documentation ). Because i could have 100 functions that i going to pass to child components or using in this component and so on.

ddeadlink
  • 249
  • 2
  • 13

2 Answers2

1

You can do this...

class ItemBox extends Component {

  someFn = ()=>{
    console.log(this)
  }
  constructor(props){
    super(props);
  }

  render(){
    return (
      <div onClick={this.someFn}>bla<div/>
    )
  }
};
hazardous
  • 10,627
  • 2
  • 40
  • 52
1

I usually do this:

class SomeComponent extends Component {
    _handleClick = () => {
         console.log(this)
    }
    render() {
        return (
            <div onClick={this._handleClick}>bla</div>
        )
    } 
}
thedude
  • 9,388
  • 1
  • 29
  • 30