代码之家  ›  专栏  ›  技术社区  ›  Thomas

在React/Formik中有条件地渲染属性

  •  0
  • Thomas  · 技术社区  · 5 年前

    只有当屏幕尺寸低于某个屏幕尺寸时,我才需要在Formik Input上显示标签属性。为此,我需要有条件地渲染标签属性。

    有没有一种更优雅(干燥?)的方法可以做到这一点,而不仅仅是这样:

    if (smallScreen) {
        <Input
            label="Unit"
            type="text"
            name="unit"
            value={values.unit}
        />  
    } else {
        <Input
            type="text"
            name="unit"
            value={values.unit}
        />
    }
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   Henrik Erstad    5 年前

    如果将反应道具设置为 null ,react将忽略它:

        <Input
            label={smallScreen ? "Unit" : null}
            type="text"
            name="unit"
            value={values.unit}
        /> 
    
        2
  •  0
  •   cool_code    5 年前
    
    const label =smallScreen? { label : "Unit"} : null
    
    <Input
    
            type={smallScreen? Unit }
            name="unit"
            value={values.unit}
            {...label}
        />