使用material-ui的TextField和getInputProps在输入旁边创建标签

时间:2019-02-07 10:35:24

标签: javascript reactjs material-ui downshift

我正在使用material-ui TextField为带有downshift的提前选择器类型组件创建输入和标签。

我看过demos,并且知道了:

<FormControl fullWidth className={classname}>
    <TextField fullWidth InputProps={ inputProps } InputLabelProps={ inputLabelProps } />
</FormControl>

我的inputProps等于:

const inputProps = getInputProps({ //passed in by {...downshiftProps} on the parent
    onChange, onKeyDown, disabled, error, label, value: inputValue,
    startAdornment: selectedItems.map(item => ...)
});

const inputLabelProps = getLabelProps({ //passed in by {...downshiftProps} on the parent
    disabled, required, error, disabled, shrink: true, id: inputProps.id
});

我的前任在material-ui InputLabel组件上定义了这些inputLabelProps属性,但是为了使aria-labelledbyby属性起作用,我只使用了一个TextField

打印输入和标签道具的内容会得到:

//labelProps
{
    disabled: false,
    error: false,
    htmlFor: "downshift-0-input",
    id: "downshift-0-label",
    required: undefined,
    shrink: false
}

//inputProps
{
    aria-activedecendant: null,
    aria-autocomplete: "list"
    aria-controls: null,
    aria-labelledby: "downshift-0-label",
    autoComplete: "off"
    disabled: false,
    error: false,
    id: "downshift-0-input",
    onBlur: f(event),
    onChange: f(event),
    onKeyDown: f(event),
    startAdornment: [],
    value: ""
}

我的问题是没有标签呈现给DOM。我得到的最接近的是带有label属性的div,它包装了输入,但什么也不显示。

p.s。我见过Material-ui textfield with label,但我不认为FloatingLAbelText不再存在了吗?答案中的链接已过期,并且与propGetters模式不兼容。

1 个答案:

答案 0 :(得分:1)

以下是注释中提到的demo的简化版本:

Edit Material demo

该演示的DownshiftMultiple部分使用了标签。我只在沙箱中包含了第一个降档演示,但是对其进行了修改,使其以与“多个”演示相同的方式使用标签。该标签不属于InputLabelProps,它只是TextField的一个属性。在演示中,这有点令人困惑,因为在传递给label的对象上将renderInput指定为属性,因此它只是作为...other对象的一部分而结束了传播到TextField

如果您查看TextField的相关代码,则会看到:

    {label && (
      <InputLabel htmlFor={id} ref={this.labelRef} {...InputLabelProps}>
        {label}
      </InputLabel>
    )}

在这里您看到InputLabelProps不会影响标签的内容,只会影响其他影响其呈现的属性,因此您需要将label作为属性直接在TextField上。