【问题标题】:Reusable TextField in ReactReact 中的可重用文本字段
【发布时间】:2021-01-09 06:01:29
【问题描述】:

我在 React 的 Material UI 中使用了可重用的 TextField,但我在使用条件时遇到了问题。如果没有传递给它,我不需要使用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}
     {prop.InputLabelProps ? InputLabelProps={{
        shrink: prop.InputLabelProps,
      }} : ''}
    />

【问题讨论】:

  • @Jayce444。伟大的!谢谢。请把它作为答案
  • 好的,已添加

标签: reactjs material-ui react-hooks react-material


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      我想知道这种语法是否有效。如果您的条件不匹配,您可以做的是传递一个未定义的值,如下所示:

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

      【讨论】:

        猜你喜欢
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 2016-10-23
        • 1970-01-01
        • 1970-01-01
        • 2021-03-24
        • 2020-08-22
        • 2021-12-22
        相关资源
        最近更新 更多