React 中的可重用 TextField

Reusable TextField in React

我在 React 的 Material UI 中使用可重复使用的 TextField,但我在使用条件时遇到问题。如果没有传递给它,我不需要使用 InputLabelProps

请检查下面我的可重复使用的 TextField

    <TextField
      fullWidth
      type={prop.type}
      label={prop.label}
      name={prop.name}
      variant="outlined"
      value={prop.value}
      onChange={prop.handleChange}
      onBlur={prop.onBlur}
      helperText={prop.helperText}
      error={prop.error}
     {prop.InputLabelProps ? InputLabelProps={{
        shrink: prop.InputLabelProps,
      }} : ''}
    />

您可以通过在三元运算符之前添加条件语句来实现此目的,

     {prop.InputLabelProps && prop.InputLabelProps ? InputLabelProps={{
        shrink: prop.InputLabelProps,
      }} : ''}

我想知道该语法是否有效。如果您的条件不符合以下条件,您可以做的是传递一个未定义的值:

<TextField
      fullWidth
      type={prop.type}
      label={prop.label}
      name={prop.name}
      variant="outlined"
      value={prop.value}
      onChange={prop.handleChange}
      onBlur={prop.onBlur}
      helperText={prop.helperText}
      error={prop.error}
      InputLabelProps=
      {
        props.InputLabelProps 
        ? { shrink: props.InputLabelProps } 
        : undefined
      }
    />

如果它不存在,只需将其设置为未定义:

InputLabelProps={prop.InputLabelProps ? { shrink: prop.InputLabelProps } : undefined}.

如果你在大多数情况下将 prop 设置为 undefined,它会表现得就像你根本没有通过它