-2

All:

I am pretty new to React, say I have a very simple case:

var React = require("react");
var ReactDOM = require("react-dom");

var Todo = React.createClass({
    render: function() {
        return (<div>Hello there 
            <button id="switch_func">Switch</button>
        </div>);
    }
});
ReactDOM.render(<Todo />, document.getElementById("div1"));

What I am trying to bind is:

There are multiple handler functions, each time when that button switch_func gets clicked, it will randomly choose another handlers and bind to itself.

But I do not know how to bind it like in AngularJS or jQuery, cos I am not sure if I can do same thing to the virtual DOM:

$("button#switch_func").on("click", function(){
    $(this).off("click");
    $(this).on("click", anotherHandler);
});
Kuan
  • 11,149
  • 23
  • 93
  • 201
  • Why would you want to unbind and rebind the same event type? Just put `aRandomHandler()` inside the `anotherHandler` function... – David Hellsing Nov 25 '15 at 21:00
  • @David thanks, I do not quite get your idea, could you show me a little code snippet? What I want is totally change the click handler function – Kuan Nov 25 '15 at 21:03
  • Instead of changing the handler function, you can change a function *inside* the handler function: `.on('click', function() { randomFunction() })` – David Hellsing Nov 25 '15 at 21:47
  • @David Thanks, but how do I replace the body of click handler function, all the handler functions are outside, I can only use them. Do you mean I need to set case selection for different handler? But in that case, It means I need to know what function I have, right? – Kuan Nov 25 '15 at 22:11
  • Something like this? https://jsfiddle.net/tj4rw78j/ – David Hellsing Nov 26 '15 at 12:32

1 Answers1

0

To bind functions you can use onClick Simply put

<button onClick={this.handleClick}>Switch</button> 

And handle the click event on the component's function:

var Todo = React.createClass({
    handleClick: function(){
        //put your function here!
    },
    //other functions in your component (e.g. render, getInitialState, etc)

});
luchosrock
  • 712
  • 10
  • 24
  • Thanks, so this means each time I click the button, React probably need to render the button again? – Kuan Nov 25 '15 at 21:01
  • @Kuan I believe I didn't quite get your question. Maybe you should take a look into this http://stackoverflow.com/questions/30845910/how-do-i-set-state-of-sibling-components-easily-in-react – luchosrock Nov 26 '15 at 12:21