微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在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,你应该包装它.

你真正想要做的是修改Control的render()方法添加一个自定义的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的prop传递的onKeyPress,以支持您的自定义onKeyPress.

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐