最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How does input value stay same even though component re-render? - Stack Overflow

programmeradmin5浏览0评论

I have a very basic react ponent as you can see below. So as far as I know every time state value change, this ponents re-render. But the thing I want to know, if the ponent 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;

I have a very basic react ponent as you can see below. So as far as I know every time state value change, this ponents re-render. But the thing I want to know, if the ponent 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;
Share Improve this question asked Oct 6, 2021 at 15:25 Jantoma21Jantoma21 4956 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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 ponent is recreated and assigned the initial state it began with.

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. 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;
发布评论

评论列表(0)

  1. 暂无评论