简体   繁体   中英

react antd input defaultValue is not displayed

I am using the Input component of react,antd.
If you enter more than 10 characters, an error will be displayed.
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.
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. DefaultValue and onChange event will not give you the expected output when you use them inside of form element. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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