RN的NumberInput組件

import React from 'react';
import {StyleSheet, TextInput, TextInputProps, TextStyle} from 'react-native';

interface Props extends Omit<TextInputProps, 'value'> {
  style?: TextStyle;
  min?: number;
  max?: number;
  value?: string;
  onChangeValue: (value?: string) => any;
  minus?: boolean;
  decimal?: boolean;
}
export default function (props: Props) {
  const {decimal = false, minus = false} = props;
  const {style, value = '', onChangeValue, min, max, ...other} = props;

  function onChangeText(val: string) {
    // 沒有輸入值直接返回
    if (!val) {
      onChangeValue('');
      return;
    }
    // 不能輸入小數
    if (!decimal && val.includes('.')) {
      onChangeValue(val.indexOf('.') > 0 ? value : '');
      return;
    }
    // 不能輸入負數
    if (!minus && val.includes('-')) {
      onChangeValue('');
      return;
    }
    // 能輸入小數但是輸入的規(guī)則不對
    let boo =
      val.includes('.') &&
      (val.indexOf('.') == 0 || val.replace('.', '').length != val.length - 1);
    if (decimal && boo) {
      onChangeValue(value);
      return;
    }
    // 能輸入負數但是輸入的規(guī)則不對
    boo =
      val.includes('-') &&
      (val.indexOf('-') > 0 || val.replace('-', '').length != val.length - 1);
    if (minus && boo) {
      onChangeValue('');
      return;
    }
    // 能輸入負數切只輸入了-符號時
    if (val == '-') {
      onChangeValue(val);
      return;
    }
    let v = Number(val);
    // 沒有最大值和最小值限制
    if (min == null && max == null) {
      onChangeValue(val);
      return;
    }
    // 最大值和最小值都有
    if (min != null && max != null && v <= max && min <= v) {
      onChangeValue(val);
      return;
    }
    // 只有最小值
    if (min != null && v < min) {
      onChangeValue(value);
      return;
    }
    // 只有最大值
    if (max != null && max <= v) {
      onChangeValue(value);
      return;
    }
  }

  return (
    <TextInput
      {...other}
      style={[st.input, style]}
      keyboardType="numeric"
      value={String(value)}
      onChangeText={onChangeText}
    />
  );
}

const st = StyleSheet.create({
  input: {},
});

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容