简体   繁体   中英

Access props and state of current component in React JS within an event handler

I am using Highcharts.js in conjunction with React.js. I want to re-render the view when a user clicks a point in Highcharts. To do this, I need to access the props variable in the click handler . Normally, I would just use this.props to update the props, but this won't work in an event handler. Therefore, how do I access the current component as a variable in the event handler so I can access its props? Is there a better way of doing what I am trying to do?

My config variable for HighCharts looks something like this. To clarify, this code is coming from the render function of the same component.

var config = {
      ...
      plotOptions: {
          series: {
              cursor: 'pointer',
              point: {
                  events: {
                      click: function (event) {
                        //the `this` variable does not have props or state here
                        //`this` refers to the point object on the graph here
                      }
                  }
              }
          }
      },
    };

Thanks for your help.

You could define the click handler function somewhere outside the config variable, and it should have access to everything outside the scope of the event.

myRerenderFunction(e) { /* do something */ } // define function here...

var config = {
      ...
          events: {
              click: myRerenderFunction // ...and it's accessible since they're defined in the same scope
          }
    };

Or you could just put the rerendering itself outside the click handler.

myRerenderFunction(e) { /* do something */ } // This is now a closure...

var config = {
      ...
          events: {
              click: function(e) {
                  /* Do something with the event */
                  myRerenderFunction(e); // ...which means you can access it from inside the click handler function
              }
          }
    };

Or you could just store the current this as a closure.

var whateverScopeThisIs = this;

var config = {
      ...
          events: {
              click: function(e) {
                  /* Do something with the event */
                  whateverScopeThisIs.doSomething(e);
              }
          }
    };

You've got plenty of options, something along those lines should work.

Try to use

events: {
   click: function (event) {
       window.ReactNativeWebView.postMessage(event)
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM