简体   繁体   中英

React input defaultValue re-rendering

I'm using form with react and I'm having trouble updating my input values. I have two listing buttons. These buttons allow me to call different json objects and transfer them to the input. And I use these buttons respectively. Some json objects may have similar keys. There is no change in the inputs where these similarities are transferred. While there is no problem in different keys, there is no change in the input for the same keys. I write values from json as defaultValue to the input. There is no change in defaultValues. I used a placeholder to test it. the placeholder continues to work without any problems. However, defaultValue is not updated.

{Object.keys(props.activeElement).map((key) => (
          <Form.Item label={key} name={key}>
            {inputRender(key)}
          </Form.Item>
  ))}

When the relevant button is clicked, the returned jsons are set to the activeElement.

const inputRender = (key) => {
    return <Input defaultValue={props.activeElement[key]} />;
  };

Can you help me?

The defaultValue is cached on the first render. So even when props.activeElement[key] points to a new value, the input's value doesn't change.

More about that on antd's FAQ .

I solved the problem with the use of ref. I created a ref value.

const formRef = useRef ();

On button click i ran this.

formRef.current.setFieldsValue ({... json});

And I used this refi on my form.

ref = {props.formRef}

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