TeaWeb/shared/js/ui/react-elements/ReactComponentBase.ts

32 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-04-06 16:28:15 +02:00
import * as React from "react";
export abstract class ReactComponentBase<Properties, State> extends React.Component<Properties, State> {
constructor(props: Properties) {
super(props);
this.state = this.default_state();
this.initialize();
}
protected initialize() { }
protected abstract default_state() : State;
2020-04-10 20:57:50 +02:00
updateState(updates: {[key in keyof State]?: State[key]}, callback?: () => void) {
if(Object.keys(updates).findIndex(e => updates[e] !== this.state[e]) === -1) {
if(callback) setTimeout(callback, 0);
return; /* no state has been changed */
2020-04-10 20:57:50 +02:00
}
this.setState(Object.assign(this.state, updates), callback);
2020-04-06 16:28:15 +02:00
}
protected classList(...classes: (string | undefined)[]) {
return [...classes].filter(e => typeof e === "string" && e.length > 0).join(" ");
}
protected hasChildren() {
const type = typeof this.props.children;
if(type === "undefined") return false;
return Array.isArray(this.props.children) ? this.props.children.length > 0 : true;
}
}