我使用 react typescript 开发了编辑通知页面。我从数据库中获取通知标题并将该值设置为自定义输入组件,如下所示
let notificationTitle: string = "Notification Test"; // getting from db
<FormInputText
label={"Notification Title:"}
value={notificationTitle}
name={`notificationTitle1`}
required={false}
placeholder={
"Text inside title tag - can include HTML text styles - bold, italic etc…"
}
labelClass={"full"}
/>
完整代码链接:https ://codesandbox.io/s/zen-aryabhata-7lfch5?file=/src/EditPage.tsx
问题:
但我无法更新输入文本框的值,并且它不断重置为从数据库传递的默认值。
反应 TypeScript 代码。
自定义输入组件
import React, {useEffect, useState} from "react";
interface Props {
label: string;
name: string;
required? : boolean;
placeholder: string;
labelClass: string;
value?: string;
}
const FormInputText: React.FC<Props> = ({
label,name,required,placeholder,labelClass,rules,value
}) => {
console.log("FormInputText",value);
const [inputValue,setInputValue] = useState<string>("");
useEffect(() => {
if(inputValue == "" && value) {
setInputValue(value);
}else{
setInputValue(inputValue);
}
});
const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
setInputValue(e.target.value);
};
return (
<>
<label className={labelClass}>
<span>{label} {(required) ? <b>*</b> : <></>}</span>
<input type="text" onChange={changeHandler} name={name}
placeholder={placeholder} value={inputValue}/>
</label>
</>
);
}
export default FormInputText;
编辑页面
import "./styles.css";
import FormInputText from "./inputtext.component";
export default function EditPage() {
let notificationTitle: string = "Notification Test"; // getting from db
return (
<div className="App">
<h1>Edit Notification</h1>
<FormInputText
label={"Notification Title:"}
value={notificationTitle}
name={`notificationTitle1`}
required={false}
placeholder={
"Text inside title tag - can include HTML text styles - bold, italic etc…"
}
labelClass={"full"}
/>
</div>
);
}
您notificationTitle
不是受控元素,EditPage
您需要将其传递给您的FormInputText
组件:
let notificationTitle: string = "Notification Test"; // getting from db
const [inputValue, setInputValue] = useState(notificationTitle);
代码在这里(可以进一步改进)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句