score:272

Accepted answer

es6 react.component doesn't auto bind methods to itself. you need to bind them yourself in constructor. like this:

constructor (props){
  super(props);
  
  this.state = {
      loopactive: false,
      shuffleactive: false,
    };
  
  this.ontoggleloop = this.ontoggleloop.bind(this);

}

score:0

if you call your created method in the lifecycle methods like componentdidmount... then you can only use the this.ontoggleloop = this.ontoogleloop.bind(this) and the fat arrow function ontoggleloop = (event) => {...}.

the normal approach of the declaration of a function in the constructor wont work because the lifecycle methods are called earlier.

score:0

in my case, for a stateless component that received the ref with forwardref, i had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

from this (onclick doesn't have access to the equivalent of 'this')

const com = forwardref((props, ref) => {
  return <input ref={ref} onclick={() => {console.log(ref.current} } />
})

to this (it works)

const usecombinedrefs = (...refs) => {
  const targetref = react.useref()

  useeffect(() => {
    refs.foreach(ref => {
      if (!ref) return

      if (typeof ref === 'function') ref(targetref.current)
      else ref.current = targetref.current
    })
  }, [refs])

  return targetref
}

const com = forwardref((props, ref) => {
  const innerref = useref()
  const combinedref = usecombinedrefs(ref, innerref)

  return <input ref={combinedref } onclick={() => {console.log(combinedref .current} } />
})

score:0

you can rewrite how your ontoggleloop method is called from your render() method.

render() {
    var shuffleclassname = this.state.toggleactive ? "player-control-icon active" : "player-control-icon"

return (
  <div classname="player-controls">
    <fontawesome
      classname="player-control-icon"
      name='refresh'
      onclick={(event) => this.ontoggleloop(event)}
      spin={this.state.loopactive}
    />       
  </div>
    );
  }

the react documentation shows this pattern in making calls to functions from expressions in attributes.

score:1

if you are using babel, you bind 'this' using es7 bind operator https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding

export default class signuppage extends react.component {
  constructor(props) {
    super(props);
  }

  handlesubmit(e) {
    e.preventdefault(); 

    const data = { 
      email: this.refs.email.value,
    } 
  }

  render() {

    const {errors} = this.props;

    return (
      <div classname="view-container registrations new">
        <main>
          <form id="sign_up_form" onsubmit={::this.handlesubmit}>
            <div classname="field">
              <input ref="email" id="user_email" type="email" placeholder="email"  />
            </div>
            <div classname="field">
              <input ref="password" id="user_password" type="new-password" placeholder="password"  />
            </div>
            <button type="submit">sign up</button>
          </form>
        </main>
      </div>
    )
  }

}

score:2

in my case this was the solution = () => {}

methodname = (params) => {
//your code here with this.something
}

score:3

you should notice that this depends on how function is invoked ie: when a function is called as a method of an object, its this is set to the object the method is called on.

this is accessible in jsx context as your component object, so you can call your desired method inline as this method.

if you just pass reference to function/method, it seems that react will invoke it as independent function.

onclick={this.ontoggleloop} // here you just passing reference, react will invoke it as independent function and this will be undefined

onclick={()=>this.ontoggleloop()} // here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object

score:12

i ran into a similar bind in a render function and ended up passing the context of this in the following way:

{somelist.map(function(listitem) {
  // your code
}, this)}

i've also used:

{somelist.map((listitem, index) =>
    <div onclick={this.somefunction.bind(this, listitem)} />
)}

score:34

write your function this way:

ontoggleloop = (event) => {
    this.setstate({loopactive: !this.state.loopactive})
    this.props.ontoggleloop()
}

fat arrow functions

the binding for the keyword this is the same outside and inside the fat arrow function. this is different than functions declared with function, which can bind this to another object upon invocation. maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.dosomethingwith(x)).

score:108

there are a couple of ways.

one is to add this.ontoggleloop = this.ontoggleloop.bind(this); in the constructor.

another is arrow functions ontoggleloop = (event) => {...}.

and then there is onclick={this.ontoggleloop.bind(this)}.


Related Query

More Query from same tag