蚂蚁设计中的输入限制字符

Jur*_*can 1 javascript typescript reactjs antd

我有带输入的蚂蚁设计表单,我需要限制一些字符在输入中写入。

<Form.Item
              {...formItemLayout}
              label={this.props.intl.formatMessage({ id: 'customer.form.zipCode' })}
            >
              {getFieldDecorator('zip_code', {
                validateTrigger: 'onBlur',
                initialValue: this.props.addressFormDefaults ? this.props.addressFormDefaults.zip_code : '',
                rules: [
                  {
                    transform: (value) => typeof value === 'string' ? value.trim() : undefined,
                    required: true, message: this.props.intl.formatMessage({ id: 'validation.requiredField' }),
                  },
                ],
              })(
                <Input
                  type="number"
                  size="large"
                  className={this.props.useSmartForm ? `${this.props.smartFormClassInstance} ${SMARTFORM_CLASS.ZIP}` : undefined}
                  form={this.props.formId}
                  disabled={this.props.formDisabled}
                />,
              )}
            </Form.Item>
Run Code Online (Sandbox Code Playgroud)

所以理想的解决方案是添加一些按键事件并验证它

<Input
  type="number"
  onKeyDown={(event) => {
    // some validation;
    if (someValidation()) {
      return true;
    }
    return false;
  }}
/>;
Run Code Online (Sandbox Code Playgroud)

但从 ts 定义

onKeyPress?: KeyboardEventHandler<T>;
type React.KeyboardEventHandler<T = Element> = (event: KeyboardEvent<T>) => void
Run Code Online (Sandbox Code Playgroud)

它的空函数。当我尝试返回 false 时,它​​不会限制。ant 设计不知何故迟钝,不从这个回调返回值。甚至不应该允许用户编写它。

另外我不使用任何状态,只使用事件的初始值。

有没有解决方案如何添加经典的 onKeyPress、onKeyDown 等输入事件,而不是蚂蚁设计事件?

谢谢

Chr*_* B. 5

前几天我在 Antd 输入上实现了类似的东西,使用另一个答案中的通用函数。这按预期工作,只需为您想要允许的任何字符编写一个正则表达式,React.KeyboardEvent用作参数:

const onKeyPress = (e: React.KeyboardEvent) => {
   const specialCharRegex = new RegExp("[a-zA-Z0-9@.' ,-]");
   const pressedKey = String.fromCharCode(!e.charCode ? e.which : e.charCode);
   if (!specialCharRegex.test(pressedKey)) {
      e.preventDefault();
      return false;
   }
}
Run Code Online (Sandbox Code Playgroud)

更新:您使用的是什么版本的 AntD,您在哪里看到该定义?我使用的是 3.23.1,InputProps接口没有明确定义onKeyPress. 但是 Input 组件将所有额外的 props 转发到它在 return 语句中呈现的基本 HTML 输入,所以不应该有任何类型冲突。

通常,事件处理程序不返回显式值,但默认情况下为 true,并且可以返回false以指示事件已被取消,就像上面的函数一样。至于为什么返回类型为 void 的函数会允许返回 false,这是 TypeScript 故意造成的异常,this answer对此进行了深入解释。