反应。 onCopy事件的preventDefault()不起作用 [英] React. preventDefault() for onCopy event does not work

查看:84
本文介绍了反应。 onCopy事件的preventDefault()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚如何使onCopy事件中的剪贴板事件返回 false 。我用于测试 onCopy 处理程序和 e.preventDefault()方法。但文本被无限制地复制到缓冲区!我错过了什么?

I'm trying to figure out how to make the clipboard events return false on the onCopy event. I use for test the onCopy handler and e.preventDefault() method. But text is copied without obstacles to the buffer! What is I miss?

提前谢谢你。

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import ReactDOMServer from 'react-dom/server';
import './index.css';


class Copy extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      time: '',
      timer: false,
      counter: 0
    };

    this.handlerCopy = this.handlerCopy.bind(this);
  }

  handlerCopy(e) {

    e.preventDefault(); // must prevent the current event

    this.setState(prevState => ({
      counter: prevState.counter + 1
    }));

    alert('Don\'t copy it!');
  }

  render() {
    return (
      <React.Fragment>
        <p onCopy={this.handlerCopy}>Copy me!</p>
        <p>Copy count: {this.state.counter}</p>
      </React.Fragment>
    );
  }
}

ReactDOM.render(
<Copy />,
document.getElementById('root'));


推荐答案

这是一个非常好的问题!

It's a really good question!

这是因为React的实际事件监听器也位于文档的根目录,这意味着click事件已经冒泡到根目录。您可以使用 e.nativeEvent.stopImmediatePropagation()来阻止其他事件侦听器。

This is happen, beause React’s actual event listener is also at the root of the document, meaning the click event has already bubbled to the root. You can use e.nativeEvent.stopImmediatePropagation() to prevent other event listeners.

试一试:

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import ReactDOMServer from 'react-dom/server';
import './index.css';


class Copy extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      time: '',
      timer: false,
      counter: 0
    };

    this.handlerCopy = this.handlerCopy.bind(this);
  }

  handlerCopy(e) {
    console.log(e.target.innerHTML);
    e.preventDefault();
    e.nativeEvent.stopImmediatePropagation();

    this.setState(prevState => ({
      counter: prevState.counter + 1
    }));

    alert('Don\'t copy it!');
  }

  render() {
    return (
      <React.Fragment>
        <p onCopy={this.handlerCopy}>Copy me!</p>
        <p>Copy count: {this.state.counter}</p>
      </React.Fragment>
    );
  }
}

ReactDOM.render(
<Copy />,
document.getElementById('root'));

这篇关于反应。 onCopy事件的preventDefault()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆