簡體   English   中英

ant 設計中的輸入限制字符

[英]Input restrict characters in ant design

我有帶輸入的 ant 設計表單,我需要限制一些字符寫入輸入。

<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>

所以理想的解決方案是添加一些按鍵事件並像

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

但從 ts 定義

onKeyPress?: KeyboardEventHandler<T>;
type React.KeyboardEventHandler<T = Element> = (event: KeyboardEvent<T>) => void

它的無效 function。 當我嘗試返回 false 它不會限制。 ant 設計在某種程度上被延遲並且不從該回調中返回值。 甚至不應該允許用戶編寫它。

我也沒有使用任何 state,只有事件的初始值。

是否有解決方案如何添加經典的 onKeyPress、onKeyDown 等輸入事件,而不是 ant 設計事件?

謝謝

前幾天我用另一個答案的通用 function 在 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;
   }
}

更新:您使用的是哪個版本的 AntD,您在哪里看到該定義? 我使用的是 3.23.1,並且InputProps接口沒有明確定義onKeyPress 然而,輸入組件將所有額外的道具轉發到基本的 HTML 輸入,它在其返回語句中呈現,因此不應該有任何類型沖突。

通常,事件處理程序不返回顯式值,但默認為 true ,並且可以返回false以指示事件已被取消,就像上面的 function 一樣。 至於為什么返回類型為 void 的 function 會允許返回 false,這是 TypeScript 故意制造的異常, 對此答案進行了深入解釋。

另外,我只是在 antd design 中使用正則表達式格式。

<Form.Item>
    {getFieldDecorator('mobile', {
        rules: [
            {
                required: true,
                pattern: new RegExp("^[0-9]*$"),
                message: "Wrong format!"
            },
        ],
    })(
        <Input
            className="form-control"
            type="text"
            placeholder="Phone number"
        />,
    )}
</Form.Item>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM