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

I have a very basic react ponent as you can see below. So as far as I know every time state value chang

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;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744362090a4570520.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信