【问题标题】:IonInput not allowing to conditionally prevent the onChange eventIonInput 不允许有条件地阻止 onChange 事件
【发布时间】:2022-10-05 07:28:10
【问题描述】:

在这个StackBlitz 项目上:https://stackblitz.com/edit/node-hxolmq?file=src%2Fmain.tsx

我有以下自定义控件...

/src/controls/IonInputMagic2.js

import { IonInput } from "@ionic/react";
import { useEffect, useState } from "react";

const IonInputMagic2 = props => {

  const { value, onChange, validityFunc, ...others } = props
  var isValidValue = validityFunc(value);
  const initialValue = (typeof value !== 'undefined' && isValidValue) ? value : '';
  const [ currentValue, setCurrentValue ] = useState(initialValue);

  useEffect(() => {
    setCurrentValue(initialValue);
  }, [initialValue]);

  const handleChange = (e) => {
    var value = e.target.value;
    if (!validityFunc(value)) {
      e.preventDefault();
      return false;
    }
    setCurrentValue(value);
    if (onChange) {
      onChange(e);
    }
  };

  return (
    <IonInput value={currentValue} onChange={handleChange} {...others} />
  );
}

export default IonInputMagic2;

你可以看到我使用Ionic 控件:IonInput

我的问题是:我有一个validityFunc(...),它决定用户输入的内容是否可以接受。根据该功能,只有数字甚至数字是允许的。但是,用户可以无限制地输入任何字符。

我有一个类似的控件:IonInputMagic1,它非常相似,但它使用HTML 内置元素:&lt;input /&gt; 而不是Ionic 控件:&lt;IonInput /&gt;。在该控件上,用户只能输入预期的内容:只有数字和偶数.

这是这两个控件之间的区别(左:有效 | 右:无效)

以下是我如何使用这两个控件:

我需要的是:要使IonInputMagic2(使用:IonInput)工作为:IonInputMagic1,用户只能输入数字甚至数字。这是因为IonInput 使用了Ionic 的所有样式和脚本,我不想通过使用&lt;input /&gt; 来破坏所有这些。

注意:我通过 DOM 检测到 IonInput&lt;input /&gt; 的包装器。

关于如何实现这一目标的任何想法?

如果可能,请分叉上面的StackBlitz 并在此处发布链接。

谢谢!

【问题讨论】:

    标签: javascript html reactjs ionic-framework ionic6


    【解决方案1】:

    这种改变起到了作用:

    这里是组件的完整代码:

    import { IonInput } from "@ionic/react";
    import { useEffect, useState } from "react";
    
    const IonInputMagic2 = props => {
    
      const { value, onChange, validityFunc, ...others } = props
      var isValidValue = validityFunc(value);
      const initialValue = (typeof value !== 'undefined' && isValidValue) ? value : '';
      const [currentValue, setCurrentValue] = useState(initialValue);
    
      useEffect(() => {
        setCurrentValue(initialValue);
      }, [initialValue]);
    
      const handleChange = (e) => {
        var value = e.target.value;
        if (!validityFunc(value)) {
          e.preventDefault();
          e.target.value = currentValue;
          return false;
        }
        setCurrentValue(value);
        if (onChange) {
          onChange(e);
        }
      };
    
      return (
        <IonInput value={currentValue} onIonInput={handleChange} {...others} />
      );
    }
    
    export default IonInputMagic2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多