简体   繁体   English

react antd input defaultValue 不显示

[英]react antd input defaultValue is not displayed

I am using the Input component of react,antd.我用的是react,antd的Input组件。
If you enter more than 10 characters, an error will be displayed.如果输入超过 10 个字符,将显示错误。
When the value of value is null, the value of value is set to 3. I checked the value in console.log() and the default value is 3.当value的值为null时,value的值设置为3,我查看了console.log()中的值,默认值为3。
The defaultValue is not applied.不应用默认值。
Somebody help me, please...有人帮帮我,拜托...

code 代码

import React, { useEffect } from "react";
import { Input, Form } from "antd";

const App = () => {
  const [value, setValue] = React.useState(null);
  const [onSave, setOnSave] = React.useState(null);
  const handleInputChange = React.useCallback((e) => {
    setValue(Number(e.target.value));
  }, []);

  const onSaveBlur = React.useCallback(() => {
    if (String(value).length < 10) {
      setOnSave(true);
    } else {
      setOnSave(false);
    }
  }, [value]);

  useEffect(() => {
    if (value === null) {
      setValue(3);
    }
  }, [value]);
  console.log(value);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Form>
        <Form.Item
          name="input"
          rules={[
            { max: 10, message: "length should be less then 10 letters!" }
          ]}
        >
          <Input
            type="number"
            value={value}
            onChange={handleInputChange}
            onBlur={onSaveBlur}
          ></Input>
        </Form.Item>
      </Form>
    </div>
  );
};

export default App;

As far as I can understand that you want to show an error message when number length becomes more than 10. This is what you've correctly applied here screenshot But as you're using input field inside of a form, there is a different approach to work with default value and onChange Event.据我所知,当数字长度超过 10 时,您想显示一条错误消息。这是您在此处正确应用的内容截图但是当您在表单内使用输入字段时,有一种不同的方法使用默认值和 onChange 事件。 DefaultValue and onChange event will not give you the expected output when you use them inside of form element.当您在表单元素中使用 DefaultValue 和 onChange 事件时,它们不会给您预期的 output 。 Here you must you form methods like this在这里你必须形成这样的方法

'https://pastebin.com/raw/1NmR4tQT'

study more about ant Design Form methods from here Learn More about ant design form methods从这里学习更多关于 ant 设计表单方法的信息 了解更多关于 ant 设计表单方法的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM