import { Component, ReactNode } from "react"; import { FontLevel, Theme } from "@Component/Theme/Theme"; import "./AttrInput.scss"; import { Icon } from "@fluentui/react"; import { Localization, AllI18nKeys } from "@Component/Localization/Localization"; interface IAttrInputProps { keyI18n: AllI18nKeys; infoI18n?: AllI18nKeys; value?: number | string; isNumber?: boolean; maxLength?: number; max?: number; min?: number; step?: number; valueChange?: (value: this["isNumber"] extends true ? number : string) => any; } interface AttrInputState { error: ReactNode; value: string; } class AttrInput extends Component { public constructor(props: IAttrInputProps) { super(props); const value = props.value ?? props.isNumber ? "0" : ""; this.state = { error: this.check(value), value: value } } private check(value: string): ReactNode { // 长度校验 const maxLength = this.props.maxLength ?? 32; if (value.length > maxLength) { return } if (this.props.isNumber) { const praseNumber = (value as any) / 1; // 数字校验 if (isNaN(praseNumber)) { return } // 最大值校验 if (this.props.max !== undefined && praseNumber > this.props.max) { return } // 最小值校验 if (this.props.min !== undefined && praseNumber < this.props.min) { return } } return undefined; } private handelValueChange = () => { if (!this.state.error && this.props.valueChange) { this.props.valueChange(this.state.value); } } private changeValue = (direction: number) => { if (this.state.error) { return; } else { let newVal = (this.state.value as any / 1) + (this.props.step ?? 1) * direction; // 最大值校验 if (this.props.max !== undefined && newVal > this.props.max) { newVal = this.props.max; } // 最小值校验 if (this.props.min !== undefined && newVal < this.props.min) { newVal = this.props.min; } this.setState( { value: newVal.toString() }, () => this.handelValueChange() ); } } public render(): ReactNode { return
{ this.props.isNumber ?
this.changeValue(-1)} >
: null } { this.setState({ error: this.check(e.target.value), value: e.target.value }, () => this.handelValueChange()); }} > { this.props.isNumber ?
this.changeValue(1)} >
: null }
{
{this.state.error}
}
} } export { AttrInput };