K
K
KnightForce2017-03-06 11:36:27
React
KnightForce, 2017-03-06 11:36:27

React. How to dynamically hang handlers?

How to dynamically hang handlers?
In jQuery, you can write anywhere on an element:

element.on("click",function(){});
element.off("click");

How to do something like this in React?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2017-03-06
@KnightForce

import React, { Component } from 'react';

class MyComponent extends Component {
    // standard function bind
    constructor(props) {
        super(props);
        
        this.onClickBar = this.onClickBar.bind(this);
    }
    
    onClickBar(event) {
        // valid "this" only if bound in constructor
    }

    // babel-plugin-transform-class-properties is required for this syntax
    onClickFoo = (event) => {
        // "this" is always valid
    };
    
    render() {
        return (
            <div>
                <button onClick={this.onClickFoo}>foo</button>
                <button onClick={this.onClickBar}>bar</button>
            </div>
        );
    }
}

// EDIT
Store a flag in the state of the component, according to which you will return at the beginning of the handler.
It's easier to do setState + idle render than to write crutches by removing/adding event listeners.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question