[英]React - Material UI - TextField controlled input with custom input component with custom props
如何將自定義道具傳遞給 inputComponent?
例如,我有一個 MuiTextField 組件:
const CustomerSocialMask = React.forwardRef<HTMLElement, CustomProps>(
function CustomerSocialMask(props, ref: any) {
// deploy test
const { onChange, ...other } = props;
return (
<IMaskInput
{...other}
mask="000.000.000-00"
definitions={{
'#': /[1-9]/,
}}
inputRef={ref}
onAccept={(value: any) =>
onChange({ target: { name: props.name, value } })
}
overwrite={false}
/>
);
},
);
<MuiTextField
sx={{
'& input[type=number]': {
MozAppearance: 'textfield',
},
'& input[type=number]::-webkit-outer-spin-button': {
WebkitAppearance: 'none',
margin: 0,
},
'& input[type=number]::-webkit-inner-spin-button': {
WebkitAppearance: 'none',
margin: 0,
},
}}
variant="standard"
multiline={data.fieldType === FieldType.LONG_TEXT}
placeholder={data.settings.placeholder}
fullWidth
type={inputType}
InputProps={{
startAdornment: prefix && (
<InputAdornment position="start">
<Typography color="text.primary">{prefix}</Typography>
</InputAdornment>
),
endAdornment: suffix && (
<InputAdornment position="start">
<Typography color="text.primary">{suffix}</Typography>
</InputAdornment>
),
inputComponent: CustomerSocialMask,
}}
name={name}
onChange={
(data.settings as ShortTextSettings).valueType ===
ValueType.CURRENCY || path === PersonalDetail.PHONE
? onChange
: handleChange
}
onBlur={handleBlurWithFix}
value={valueAdjusted}
error={!!error}
helperText={error}
/>
當我嘗試將自定義道具傳遞給 inputComponent 時,例如:
inputComponent: <CustomerSocialMask customProp={something}/>,
我收到以下錯誤:
Failed prop type: Invalid prop `inputComponent` of type `object` supplied to `ForwardRef(Input2)`, expected a single ReactElement type.
所以我必須只為 inputComponent 提供 refs,但我不能將外部數據/props 傳遞給 forwardRef 組件。 我想在CustomerSocialMask 組件示例中使用 customProp。 我該怎么做? 在docs上找不到任何內容。
該解決方案似乎與您正在做的非常接近,您只需將 function 傳遞給 inputComponent。
inputComponent: (props) => <CustomerSocialMask {...props} myCustomPropName={doSomething} />
你好 MUITextfield inputProps 屬性只能接受具有普通輸入標簽的類型可以接受(取決於類型),但是您可以使用 MUI Input
組件傳遞自定義組件來使用,並且 inputProps 可用,因此您可以傳遞您的自定義字段的道具。
我在這個沙箱中創建了一個快速草稿: https://codesandbox.io/s/react-mui-using-a-custom-component-with-input-compnent-zysvji?file=/src/App.tsx
我希望這有幫助。 乙
Material UI TextField
提供了一些“道具”樣式屬性來將配置應用於組合以進行輸入的子組件。
值得注意的兩個是:
InputProps
:這為基於variant
屬性(即OutlinedInput
、 FilledInput
等)選擇的 Material UI 組件提供屬性。inputProps
:這為正在使用的底層輸入提供屬性,默認情況下這是一個input
。 使用InputProps.inputComponent
時,底層輸入將替換為提供的組件,這允許您使用inputProps
傳遞額外的屬性來配置自定義輸入。
例子:
<TextField
InputProps={{
inputComponent: CustomerSocialMask,
}}
inputProps={{
customProp: something
}}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.