输入的文本类型在状态更改时没有重新呈现。

huangapple go评论68阅读模式
英文:

Input of type text not re-rendering on state change

问题

我有一段代码
App.js

import React, { useState} from 'react';
import Input from './Components/Input';
export default function App() {
  const [state,setState]=useState(0);
  const handler=()=>{
    setState(prev=>prev+1);
  }
  return <>

  <Input></Input>
  <button onClick={handler}>Change state</button>
  <p>{state}</p>
  </>
}
和Input.js:

export default function Input()
{
return
}

问题在于,当点击按钮更改状态时,Input 没有重新渲染,尽管应该重新渲染,因为父级正在重新渲染,我知道事实上子级会重新渲染,即使它们的 props 在父级重新渲染时没有更改。它保留我在输入框中输入的值并且没有重新渲染。当我使用`<input type="text"></input>`或`<Input prop="dummyProp"></Input>`代替`<Input></Input>`时也是这种情况。我没有使用严格模式。
英文:

I have a piece of code:
App.js


import React, { useState} from &#39;react&#39;;
import Input from &#39;./Components/Input&#39;;
export default function App() {
  const [state,setState]=useState(0);
  const handler=()=&gt;{
    setState(prev=&gt;prev+1);
  }
  return &lt;&gt;

  &lt;Input&gt;&lt;/Input&gt;
  &lt;button onClick={handler}&gt;Change state&lt;/button&gt;
  &lt;p&gt;{state}&lt;/p&gt;
  &lt;/&gt;  

}

and Input.js:

export default function Input()
{
    return &lt;input type=&quot;text&quot;&gt;&lt;/input&gt;
}

The problem is that on changing the state by clicking on the button the Input is not re-rendering while it should as the parent is re-rendering and I know for a fact that children re-render even if their props don't change when parent re-renders. It keeps the value that I type in the input and does not re-render. Same is the case when I use &lt;input type=&quot;text&quot;&gt; or &lt;Input prop=&quot;dummyProp&quot;&gt;&lt;/Input&gt; instead of &lt;Input&gt;&lt;/Input&gt;.I am not using strict mode.

答案1

得分: 1

您必须将状态作为参数传递给组件

import React, { useState } from 'react';

function Input({ state }) {
    return <input type="text" value={state}></input>;
}

export function App(props) {
    const [state, setState] = useState(0);
    const handler = () => {
        setState((prev) => prev + 1);
    }
    return <>
        <Input state={state}></Input>
        <button onClick={handler}>Change state</button>
        <p>{state}</p>
    </>;  
}
英文:

You have to pass the state as a param to the component

import React , { useState} from &#39;react&#39;;

function Input({ state })
{
    return &lt;input type=&quot;text&quot; value={state}&gt;&lt;/input&gt;
}

export function App(props) {
   const [state,setState]=useState(0);
  const handler=()=&gt;{
    setState(prev=&gt;prev+1);
  }
  return &lt;&gt;

  &lt;Input state={state}&gt;&lt;/Input&gt;
  &lt;button onClick={handler}&gt;Change state&lt;/button&gt;
  &lt;p&gt;{state}&lt;/p&gt;
  &lt;/&gt;  
}

huangapple
  • 本文由 发表于 2023年2月8日 18:58:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定