![](/img/trans.png)
[英]How to ensure that an extending class must set property values in 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
,你應該包裝它。
你真正想做的是修改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
傳遞的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.