我有一个父组件,在其中初始化一些状态,然后将其传递给子组件,以便它们可以更新它。但是,当触发更新时,组件树将重新渲染,我的输入将失去焦点。添加key
没有帮助。
// App.tsx
export function App(props) {
const useVal = useState("");
return (
<Router>
<Switch>
<Route
exact
path="/"
component={() => (
<StartScreen
useVal={useVal}
/>
)}
/>
// ...
</Router>
);
}
// StartScreen.tsx
interface StartScreenProps {
useVal: [string, React.Dispatch<React.SetStateAction<string>>];
}
function bindState<T>(
[value, setState]: [T, React.Dispatch<React.SetStateAction<T>>]
) {
return {
value,
onChange: ({ value }: { value: T }) => setState(value)
}
}
export const StartScreen = (props: StartScreenProps) => {
return (
<form>
<InputField
key="myInput"
{...bindState(props.useVal)}
/>
</form>
);
}
所以,现在当我开始输入我的 InputField
时(这基本上是 <input>
上的包装器)在 StartScreen.tsx
上,随着组件完全重新渲染,输入不断失去焦点(我可以在 DOM 中看到它)。
最佳答案
发生这种情况是因为您将一个函数传递给 Route
的 component
属性(我假设您正在使用 react-router-dom
):
来自docs :
If you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component.
要解决此问题,请使用 render
属性:
<Route
exact
path="/"
render={() => (
<StartScreen
useVal={useVal}
/>
)}
/>
This allows for convenient inline rendering and wrapping without the undesired remounting explained above.
关于javascript - React 向下传递钩子(Hook)会导致重新渲染并失去对输入的关注,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63492066/