[英]Losing focus on input field after typing a character in React with redux-form library
我正在使用redux-form庫在 React 中工作。 我想在功能組件中創建帶有 2 個字段的簡單表單。 在其中一個字符中只輸入 1 個字符后,我失去了焦點。 我創建了函數renderInput ,它返回 Material UI TextField 輸入。 使用本機 HTML 輸入,我可以觀察到相同的錯誤。 我試圖將renderInput移動到組件內部,但它沒有幫助我。
下面我展示了我的功能組件實現:
import React from "react";
import {Field, InjectedFormProps, reduxForm} from "redux-form";
import IStream from "./types/Istream";
import {CommonFieldProps, GenericField, WrappedFieldProps} from "redux-form/lib/Field";
import {TextField} from "@material-ui/core";
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
'& .MuiTextField-root': {
margin: theme.spacing(1),
width: '25ch',
},
},
}),
);
export const streamMethods = () => {
const renderInput = (formProps: WrappedFieldProps): JSX.Element => {
return (
<TextField
required
id="outlined-required"
value={formProps.input.value}
onChange={formProps.input.onChange}
/>
);
}
return {
renderInput,
}
}
const StreamCreate = (props: InjectedFormProps<IStream>) => {
const classes = useStyles();
return (
(
<form className={classes.root}>
<Field name="title" component={streamMethods().renderInput}/>
<Field name="description" component={streamMethods().renderInput}/>
</form>
)
)
}
export default reduxForm<IStream, {}>({
form: "streamCreate" // name of using form
})(StreamCreate);
通常,如果您在某個字段上失去焦點,則意味着該組件會重新安裝。 當組件的key
更改或身份(組件的實際功能/類)更改時,組件會重新安裝(除其他外)。
您從streamMethods()
為每個渲染返回一個具有新標識的組件函數(實際上,每個渲染兩次)。
我試圖將
renderInput
移動到組件內部,但它沒有幫助我。
那有同樣的問題; 如果renderInput
是一個內部函數,它也會隨着渲染而改變。 (如果你真的需要在另一個(功能性)組件中聲明一個組件,你可以使用React.useMemo()
鈎子來讓它保持它的身份。)
改變事情到
const StreamInput = (formProps: WrappedFieldProps): JSX.Element => {
return (
<TextField
required
id="outlined-required"
value={formProps.input.value}
onChange={formProps.input.onChange}
/>
);
};
const StreamCreate = (props: InjectedFormProps<IStream>) => {
const classes = useStyles();
return (
<form className={classes.root}>
<Field name="title" component={StreamInput} />
<Field name="description" component={StreamInput} />
</form>
);
};
你應該是金色的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.