繁体   English   中英

在Typescript中扩展基类属性

[英]Extending base class property in Typescript

我正在尝试为ReactReduxForm的Control组件创建一个包装类来添加其他功能。 这是基类/组件定义:

export class Control<T> extends React.Component<ControlProps<T>, {}> {
    static custom: React.ComponentClass<ControlProps<HTMLInputElement>>;
    static input: React.ComponentClass<ControlProps<HTMLInputElement>>;
    static text: React.ComponentClass<ControlProps<HTMLInputElement>>;
    static textarea: React.ComponentClass<ControlProps<HTMLTextAreaElement>>;
    static radio: React.ComponentClass<ControlProps<HTMLInputElement>>;
    static checkbox: React.ComponentClass<ControlProps<HTMLInputElement>>;
    static file: React.ComponentClass<ControlProps<HTMLInputElement>>;
    static select: React.ComponentClass<ControlProps<HTMLSelectElement>>;
    static reset: React.ComponentClass<ControlProps<HTMLButtonElement>>;
    static button: React.ComponentClass<ControlProps<HTMLButtonElement>>;
}

我想覆盖所有类型的控件(例如输入,文本,文本区域等)的onKeyPress功能,这些控件是基本Control类/组件的静态属性。

这是我的派生类的骨架定义:

import * as React from "react";
import { Control } from "react-redux-form";

export class CustomControl<T> extends Control<T> { }

我希望以下功能适用于CustomControl所有控件类型(例如,text,select等):

  onKeyPress(e: any) {
    if (e.key === "Enter") {
      e.preventDefault();
    }
  }

如何使用我的`onKeyPress()功能?

而不是使用CustomControl扩展Control ,你应该包装它。

你真正想做的是修改Controlrender()方法并添加一个自定义onKeyPress 扩展Control的问题在于,您只能覆盖 Control的render方法,而不能对其中的部分进行更改。

但是,如果使用自己的组件包装 Control组件,则可以按照您希望的方式对其进行影响。

如果你看一下ControlProps<T>的定义,你会看到:

export interface ControlProps<T> extends React.HTMLProps<T> {

因为它正在扩展React.HTMLProps所以它支持onKeyPress方法作为prop。

如果我们将所有这些信息组合在一起,您可以执行以下操作:

import * as React from "react";
import { Control, ControlProps } from "react-redux-form";

export class CustomControl<T> extends React.Component<ControlProps<T>> {

    onKeyPress(e: any) {
        if (e.key === "Enter") {
            e.preventDefault();
        }
    }

    render() {
        return <Control {...this.props} onKeyPress={e => this.onKeyPress(e)} />;
    }
}

请注意,上面的实现将完全覆盖任何作为CustomControl传递的onKeyPress ,以支持您的自定义onKeyPress

如果您还想调用任何作为prop传递的onKeyPress ,您可以将以下内容添加到自定义onKeyPress函数的底部:

// After custom logic call any onKeyPress passed to this
this.props.onKeyPress && this.props.onKeyPress(e);

尝试使用等待事件触发器的EventListener覆盖基本javascript函数onKeyPress()

 document.addEventListener('keypress', yourCallBack, true); yourCallBack() { // your code } 

放在app.component.ts里面,应该没问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM