reactjs 如何在TextField MUI组件中有条件地使用属性

sirbozc5  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(171)

我想创建一个基于MUI TextField和Formik的通用组件
我已经处理了其余的 prop ,但是我不知道如何使用value和onChange来处理

<Field
   disabled={isDisabled}
   as={TextFieldStyled}
   sx={signUpFormTextField}
   label={inputLabel}
   name={inputName}
   helperText={
    <ErrorMessage name={inputName}>
     {(msg) => (
      <Typography component="span" sx={errorMessage}>
         {msg}
      </Typography>
     )}
    </ErrorMessage>
   }
   error={hasError}

   // ------------------------
   onChange={
     customOnChangeMethod ? customOnChangeMethod : defaultOnChangeMethod
   }
   value={
     customValue ? customValue : use default value
   }
   // ------------------------
  />
83qze16e

83qze16e1#

你可以这样做:

function MyFormField({
  isDisabled,
  inputLabel,
  inputName,
  hasError,
  onChange,
  customOnChange = null,
  value,
  customValue = null
  //otherProps
}) {
  return (
    <TextField
      disabled={isDisabled}
      label={inputLabel}
      name={inputName}
      error={hasError}
      //other props
      onChange={customOnChange || onChange}
      value={customValue || value}
    />
  );
}

所以customValuecustomOnChange是可选的,默认为空,只有放到组件props中才会用到。

<MyFormField
  // these are common between all your form fields:
  value={value}
  onChange={handleChange}
  //these you can put wherever you like and will override the previous ones:
  customValue={customValue}
  customOnChange={handleCustomChange}
  //...other props
/>

编辑:

为了使valueonCahnge可选,您也可以为它们使用***默认函数参数***。

(onChange = null,
customOnChange = null,
value = null,
customValue = null,)

但是您需要小心,因为在调用组件时您可能忘记提供默认和定制的属性,并且您不会看到任何错误,但是您的代码会因为两个属性都为空而中断。

typescript 版本

具有?的类型是可选的。

function MyFormField({
  isDisabled,
  inputLabel,
  inputName,
  hasError,
  //other props
  onChange = null,
  customOnChange = null,
  value = null,
  customValue = null,
}: {
  isDisabled: boolean;
  inputLabel: string;
  inputName: string;
  hasError: boolean;
  //other props types
  //change these 'any' types based on your desired design:
  onChange?: any;
  customOnChange?: any;
  value?: any;
  customValue?: any;
}) {
  return (
    <TextField
      disabled={isDisabled}
      label={inputLabel}
      name={inputName}
      error={hasError}
      //other props
      onChange={customOnChange || onChange}
      value={customValue || value}
    />
  );
}

相关问题