【问题标题】:AntDesign validation Typography editable textAnt Design 验证版式可编辑文本
【发布时间】:2020-06-30 16:54:31
【问题描述】:

我正在尝试验证用户何时输入 Antd 设计文本,这样它就不会让他输入除数字之外的其他值,并且 onchange 不会返回任何内容。

"antd": "^4.3.3", “反应”:“^16.13.1”

import React from "react";
import { Typography } from "antd";
const { Text } = Typography;

export default class Demo extends React.Component {
    state = {
        price: 0,
    };

    onChange = (price) => {
        let isValid= validatePriceRegex(price);
        console.log(isValid, "Price:", price);
        this.setState({ price});
    };

    handleChange = (e) => {
        // In this part, I want to validate the input when the user is typing the value
        console.log(e); // dont return anything
    };

    render() {
        return (
            <Text
                onChange={this.handleChange}
                editable={{ onChange: this.onChange }}
            >
                {this.state.price.toString()}
            </Text>
        );
    }
}

const validatePriceRegex = (price) => {
    const regex = /^\$?\d+(,\d{3})*(\.\d*)?$/;
    return price && regex.test(price);
};

【问题讨论】:

    标签: regex reactjs forms validation antd


    【解决方案1】:

    您似乎有 2 个关于更改功能的句柄。 handleChangehandleChange

    可编辑的文本组件只接受 editable 属性内的 onChange,所以你必须在更改功能上做同样的事情

    import React from "react";
    import { Typography } from "antd";
    const { Text } = Typography;
    
    export default class Demo extends React.Component {
      state = {
        price: 0
      };
    
      onChange = price => {
        let isValid = validatePriceRegex(price);
        console.log(isValid, "Price:", price);
        // you validate here
        if (isValid) {
          this.setState({ price });
        }
      };
    
      // handleChange = e => {
      //   // In this part, I want to validate the input when the user is typing the value
      //   console.log(e); // dont return anything
      // };
    
      render() {
        return (
          <Text editable={{ onChange: this.onChange }}>
            {this.state.price.toString()}
          </Text>
        );
      }
    }
    
    const validatePriceRegex = price => {
      const regex = /^\$?\d+(,\d{3})*(\.\d*)?$/;
      return price && regex.test(price);
    };
    

    【讨论】:

    • 谢谢,验证功能正常,但我希望用户不能看到或写信,只是格式化钱
    • 我怀疑您在编辑模式下可以控制输入。因为它在内部作为不受控制的组件进行控制。似乎没有调用 TextProp 的 onChange ,只有在保存文本时才调用 onChange 。可以看源码github.com/ant-design/ant-design/blob/master/components/…
    • 来自我的 prev exp,根据验证修改输入值(AKA 转义字符不是一个小问题,因为反应总是将光标设置到末尾。这是一个已知问题。见 github.com/facebook/react/issues/955
    • 很好,我明白了,希望这个问题可以改进
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2017-06-23
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    相关资源
    最近更新 更多