You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何限制UI Kitten Input仅输入一个小数点?

解决UI Kitten Input结合react-hook-form限制单个小数点输入的问题

这里提供两种可行方案,分别从验证拦截和实时输入过滤角度实现需求:

方案一:通过react-hook-form自定义验证规则拦截非法输入

利用react-hook-form的register方法自带的validate选项,编写规则统计输入值中的小数点数量,超过1则返回错误提示,同时结合UI Kitten Input的状态展示错误信息:

import React from 'react';
import { Input } from '@ui-kitten/components';
import { useForm } from 'react-hook-form';

const DecimalInput = () => {
  const { register, handleSubmit, formState: { errors } } = useForm();

  // 验证规则:最多允许一个小数点
  const validateSingleDecimal = (value) => {
    if (!value) return true;
    const decimalCount = (value.match(/\./g) || []).length;
    return decimalCount <= 1 || '只能输入一个小数点';
  };

  const onSubmit = (data) => {
    console.log('提交的数据:', data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input
        {...register('decimalInput', { validate: validateSingleDecimal })}
        placeholder="请输入小数"
        keyboardType="decimal-pad"
        status={errors.decimalInput ? 'danger' : 'basic'}
        caption={errors.decimalInput?.message}
      />
      <button type="submit" style={{ marginTop: 16 }}>提交</button>
    </form>
  );
};

export default DecimalInput;

该方案保留用户输入动作,通过验证提示告知错误,适合需要明确错误反馈的场景。

方案二:实时过滤输入值,直接阻止第二个小数点输入

使用react-hook-form的Controller组件包裹UI Kitten Input,在onChange事件中实时处理输入值,通过正则表达式过滤多余的小数点,让用户无法输入第二个小数点:

import React from 'react';
import { Input } from '@ui-kitten/components';
import { useForm, Controller } from 'react-hook-form';

const DecimalInput = () => {
  const { control, handleSubmit } = useForm();

  // 过滤函数:保留数字和最多一个小数点
  const filterDecimalValue = (inputValue) => {
    if (!inputValue) return inputValue;
    // 替换掉第二个及以后的小数点
    return inputValue.replace(/(\..*)\./g, '$1');
  };

  const onSubmit = (data) => {
    console.log('提交的数据:', data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="decimalInput"
        control={control}
        defaultValue=""
        render={({ field: { onChange, value } }) => (
          <Input
            value={value}
            onChange={(e) => {
              const filtered = filterDecimalValue(e.nativeEvent.text);
              onChange(filtered);
            }}
            placeholder="请输入小数"
            keyboardType="decimal-pad"
          />
        )}
      />
      <button type="submit" style={{ marginTop: 16 }}>提交</button>
    </form>
  );
};

export default DecimalInput;

该方案用户体验更流畅,输入过程中直接拦截非法内容,适合追求直观输入体验的场景。

内容的提问来源于stack exchange,提问作者julcodecode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:25:20