英文:
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 '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>
</>
}
and Input.js:
export default function Input()
{
return <input type="text"></input>
}
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 <input type="text">
or <Input prop="dummyProp"></Input>
instead of <Input></Input>
.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 '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>
</>
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论