React 中可重用的 TextField

IT技术 reactjs material-ui react-hooks react-material
2021-04-27 08:45:06

我在 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,
      }} : ''}
    />
3个回答

如果它不存在,只需将其设置为 undefined :

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

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

您可以通过在三元运算符之前添加条件语句来实现这一点,

     {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
      }
    />