简体   繁体   English

即使组件重新渲染,输入值如何保持不变?

[英]How does input value stay same even though component re-render?

I have a very basic react component as you can see below.我有一个非常基本的反应组件,如下所示。 So as far as I know every time state value change, this components re-render.据我所知,每次 state 值更改时,该组件都会重新渲染。 But the thing I want to know, if the component re-render every time I type something in input field, why input value stay the same and not going back to empty value?但我想知道的是,如果每次我在输入字段中输入内容时组件都重新渲染,为什么输入值保持不变而不返回空值?

import React, { useState } from "react";

const InputExample = () => {
  const [value, setValue] = useState("");
  console.log("render");
  return (
    <>
      <input type="text" onChange={(e) => setValue(e.target.value)} />
    </>
  );
};

export default InputExample;

You are confusing re-rendering with reinitializing.您将重新渲染与重新初始化混淆了。 Re-rendering just updates the DOM to reflect the changes in the state. It does not mean the component is recreated and assigned the initial state it began with.重新渲染只是更新 DOM 以反映 state 中的更改。这并不意味着重新创建组件并分配它开始的初始 state。

In this case, whenever the input is changed, the value variable gets updated with what was entered in the input element.在这种情况下,只要输入发生变化,值变量就会更新为在输入元素中输入的内容。

Becuase value is not set, it is considered "uncontrolled" and does the default html behavior.因为未设置值,它被认为是“不受控制的”并执行默认的 html 行为。 In order to keep it as an empty value, you'd have to do something like:为了将其保留为空值,您必须执行以下操作:

import React, { useState } from "react";

const InputExample = () => {
  const [value, setValue] = useState("");
  console.log("render");
  return (
    <>
      <input type="text" onChange={(e) => setValue(e.target.value)} value="" />
    </>
  );
};

export default InputExample;

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

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