无法在React 15中触发onCopy事件

时间:2019-03-06 14:56:49

标签: javascript reactjs

我正在尝试通过使用onCopy事件处理程序来防止文本复制到页面上。但是似乎根本没有触发该处理程序。

代码:

  handleCopy (e) {
    console.log('Hello world');
    e.preventDefault();
    e.stopPropagation();
  }

  render () {
    const { id, className, ...props } = this.props;
    const fullClassName = className ? `sr-only ${className}` : 'sr-only ok';
    return (
      <span className={fullClassName} id={id} {...props}
        onCopy={(e) => this.handleCopy(e)}>
        {this.props.children}
      </span>
    );
  }
}

样式:

.sr-only {
  user-select: none;
}

我一直在使用此post作为参考。

任何帮助将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:0)

  

正确的方法是onCopy = {this.handleCopy}。这里e是自动传递的。请尝试以下代码段。它将起作用。

handleCopy(e) {
    console.log('Hello world');
    e.preventDefault();
    e.stopPropagation();
  }
  render() {
    const { id, className, ...props } = this.props;
    const fullClassName = className ? `sr-only ${className}` : 'sr-only ok';
    return (
      <span className={fullClassName} id={id} {...props}
        onCopy={this.handleCopy}>
        {this.props.children}
      </span>
    );
  }

答案 1 :(得分:0)

class ScreenReaderMessage extends BcReactComponent {
    constructor (props) {
      super(props);
    }

    handleCopy (e) {
      console.log('Hello world');
      e.preventDefault();
      e.stopPropagation();
    }

    render () {
      const { id, className, ...props } = this.props;
      const fullClassName = className ? `sr-only ${className}` : 'sr-only ok';
      return (
        <span className={fullClassName} id={id} {...props}
            onCopy={(e)=>this.handleCopy(e)}
            onContextMenu={(e)=>this.handleCopy(e)}
          >
          {this.props.children}
        </span>
      );
    }
  }

  ScreenReaderMessage.propTypes = {
    id: PropTypes.string,
    localeKey: PropTypes.string,
    children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired
  };

  export default ScreenReaderMessage;

希望这会有所帮助。