Double click and click on ReactJS component

I have a ReactJS component that I want to have in different ways, one click and double click.

I read this question: onClick works, but onDoubleClick is ignored in the React component

<Component
    onClick={this.onSingleClick}
    onDoubleClick={this.onDoubleClick} />

And I tried it myself, and it seems that you cannot register one click and double click on the ReactJS component.

I am not sure of a good solution to this problem. I do not want to use a timer because I will have 8 of these separate components on my page.

Would it be a good decision to have another internal component inside this to handle the double-click situation?

Edit:

I tried this approach, but it does not work in the render function.

render (

    let props = {};

    if (doubleClick) {
        props.onDoubleClick = function
    } else {
        props.onClick = function
    }
    <Component
        {...props} />
);
+4
1

, , ( , , ), , , - .

render() {
    let clicks = [];
    let timeout;

    function singleClick(event) {
        alert("single click");
    }

    function doubleClick(event) {
        alert("doubleClick");
    }

    function clickHandler(event) {
        event.preventDefault();
        clicks.push(new Date().getTime());
        window.clearTimeout(timeout);
        timeout = window.setTimeout(() => {
            if (clicks.length > 1 && clicks[clicks.length - 1] - clicks[clicks.length - 2] < 250) {
                doubleClick(event.target);
            } else {
                singleClick(event.target);
            }
        }, 250);
    }

    return (
        <a onClick={clickHandler}>
            click me
        </a>
    );
}

.

, , " " 250 , , .

, ​​250 , , doubleClick -...

0

Source: https://habr.com/ru/post/1629447/


All Articles