最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use of bind when calling a function on onClick Event - Stack Overflow

programmeradmin1浏览0评论

Following is the sample code I was working on.

So basically there are two hyperlinks lets say , A and B.

I wanted when you click A, I want to console log 'You selected A', and if you select B, console log 'You selected B'.

I am confused as to why do I need to pass the parameters using bind ?

In the snippet below, console.log occurs when you click MIT but not when you click Stanford

'You clicked Stanford' is console logged as soon as I run the program and nothing happens on clicking it afterwards. 'You Clicked MIT' works perfectly on the other hand.

import React, { Component, PropTypes } from 'react';

export default class ToppersView extends Component {

  state = {
        currentSelected : 'Harvard'
  }  

  handleClick (str) {

    console.log(" You selected ",str)
  }

  render () {

      return (
         <div className = 'container'>
            <h3> University is : {this.state.currentSelected}</h3>
             <div>
              {/* Works */}
              <a onClick = {this.handleClick.bind(null,"MIT")}>#MIT</a>

              {/*Does not  work */}
              <a onClick ={this.handleClick("Stanford")}>#Stanford</a>

            </div>
            <br/> 


        </div>
        )
    }

}

Following is the sample code I was working on.

So basically there are two hyperlinks lets say , A and B.

I wanted when you click A, I want to console log 'You selected A', and if you select B, console log 'You selected B'.

I am confused as to why do I need to pass the parameters using bind ?

In the snippet below, console.log occurs when you click MIT but not when you click Stanford

'You clicked Stanford' is console logged as soon as I run the program and nothing happens on clicking it afterwards. 'You Clicked MIT' works perfectly on the other hand.

import React, { Component, PropTypes } from 'react';

export default class ToppersView extends Component {

  state = {
        currentSelected : 'Harvard'
  }  

  handleClick (str) {

    console.log(" You selected ",str)
  }

  render () {

      return (
         <div className = 'container'>
            <h3> University is : {this.state.currentSelected}</h3>
             <div>
              {/* Works */}
              <a onClick = {this.handleClick.bind(null,"MIT")}>#MIT</a>

              {/*Does not  work */}
              <a onClick ={this.handleClick("Stanford")}>#Stanford</a>

            </div>
            <br/> 


        </div>
        )
    }

}
Share Improve this question edited Nov 21, 2019 at 20:54 Zombies 25.9k44 gold badges145 silver badges230 bronze badges asked Feb 5, 2016 at 11:48 SachinSachin 3,5404 gold badges20 silver badges29 bronze badges 1
  • one returns a function, one returns nothing. onclick wants a function. – dandavis Commented Feb 5, 2016 at 11:50
Add a ment  | 

3 Answers 3

Reset to default 4

this.handleClick("Stanford") calls the function right here, while this.handleClick.bind(null,"MIT") binds the context and argument and returns the function so it can be called later.

An event listener needs a reference to a function, but your handleClick method doesn't return anything, so after it's been executed there's nothing to bind to event listener. You could modify the handleClick method to return another function which would be called on click:

handleClick (str) {
   return function(){ // this function will be used as event callback
    console.log(" You selected ",str)
   }
}
// the function will be executed and the returned function called in event callback
<a onclick ={this.handleClick("Stanford")}>#Stanford</a>
  1. What you are doing onclick = {this.handleClick("Stanford")} just calls the method immediately and returns undefined. What you want to do is pass a reference of your function, not call the function. Also bind does provide a reference of your function, but it does (and is meant) for more than that. You can just reference your function without the () in it. See #2.

  2. What you aren't doing (but maybe others who e here are doing or for those who are curious), but also isn't a good idea onClick ={this.handleClick} because you won't be able to access this once inside your event handler. Although by doing it this way, it does now set an eventhandler function. However, when that function runs, any references to this will be null (eg: as you are in reactjs, you won't be able to do useful things like this.setState({...}); Although, your code will work now so there is no need for bind to make it work.

  3. What (probably) you need to do, and why this.handleClick.bind(this) because of how this binding works in Javscript and also there isn't much value in putting hard-strings inside your callback function. If you want to reference it, do it dynamically like this e.target.innerText see the codepen for a plete and re-worked example: https://codepen.io/Zombies333/pen/yLLrLyx

There is a typo and a missing .bind here:

<a onclick ={this.handleClick("Stanford")}>#Stanford</a>

This is correct:

<a onClick ={this.handleClick.bind(null, "Stanford")}>#Stanford</a>

If you dont want to use .bind you can use arrow functions. So instead of:

handleClick (str) {

    console.log(" You selected ",str)
}

Use:

handleClick = (str) => {

    console.log(" You selected ",str)
 }
发布评论

评论列表(0)

  1. 暂无评论