我正在嘗試從一組物件和一個自定義輸入欄位中制作一個可擴展的自定義表單,我正在開發一個 React-Typescript 專案
import React, { ChangeEvent } from "react"
import { InputField } from "./InputField"
interface FormItem {
key: string
fieldType: string
placeholder: string
value: string
errorMessage: string | null
validationMethod: (validateValue : string) => string | null
}
interface FormProps {
formProps : FormItem[]
}
export const CustomForm = ({formProps} : FormProps) => {
const [FORM, SETFORM] = React.useState(formProps)
const onFormChange = (event: ChangeEvent<HTMLInputElement>) => {
const target = event.currentTarget
const findChangedValue = FORM.find(fv => fv.key === target.name)
const validationText = findChangedValue?.validationMethod(target.value)!
const newForm = FORM.map(fv => {
if( target.value === fv.key ){
return {...fv, value: target.value, errorMessage: validationText}
}
return fv
})
SETFORM(newForm)
}
return (
<>
{FORM.map(( fv ) => {
<InputField
placeholderText={fv.placeholder}
name={fv.key}
inputType={fv.fieldType}
handleChange={onFormChange}/>
})}
</>
)
}
我從一個父組件呼叫這個組件,將它作為道具發送
interface FormProps {
key: string
fieldType: string
placeholder: string
value: string
errorMessage: string | null
validationMethod: ((validateValue : string) => string | null)
}
const FORM : FormProps[] = [
{ key: "email", placeholder:"Enter your email", fieldType: "text", value: "", errorMessage: "", validationMethod: validateEmail },
{ key: "password", placeholder:"Enter your password", fieldType: "text", value: "", errorMessage: "", validationMethod: validatePassword },
]
return (
<StyledForm enabledSubmit={enableSubmit}>
<h2>Login</h2>
<CustomForm formProps={FORM}/>
</StyledForm>
)
我嘗試控制臺記錄 CustomForm 上的道具并且值到達那里就好了,但是當我運行專案時 InputFields 不會出現,我還嘗試控制臺記錄 InputField 組件中的傳入道具并且它們不會列印,就像他們一樣在 map 方法中傳遞它們后迷路了,我也嘗試在表單標簽之間包裝 map 方法
uj5u.com熱心網友回復:
你沒有從map
. 您還需要使用該key
道具并提供唯一的密鑰。
{FORM.map((fv) => (
<InputField
key={fv.key}
placeholderText={fv.placeholder}
name={fv.key}
inputType={fv.fieldType}
handleChange={onFormChange}
/>
))}
大括號改為圓括號。
圓括號(或無括號)是隱式回傳。
() => ("returning a value")
() => "returning a value"
花括號執行閉包。IE。他們需要一個 return 陳述句來回傳一個值。
() => { "doing nothing" }
() => { return "returning a value" }
有趣的是,您沒有看到錯誤的唯一原因是因為您將地圖包裝在一個片段中,我猜這允許一個無效的子節點。如果將片段更改為 div,您將看到錯誤Type 'void[]' is not assignable to type 'ReactNode'.
我還可以建議您清理型別定義嗎?
您可以只使用一種型別,而不是三個介面:
export type FormItem = {
key: string
fieldType: string
placeholder: string
value: string
errorMessage: string | null
validationMethod: (validateValue : string) => string | null
}
const FORM : FormItem[] = [...]
export const CustomForm: FC<{ formProps: FormItem[] }> = ({ formProps }) => {...}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529967.html
下一篇:使用`suppressImplicitAnyIndexErrors=false`不能將型別“字串”分配給型別“未定義”