【问题标题】:Creating a label alongside an input using material-ui's TextField and getInputProps使用 material-ui 的 TextField 和 getInputProps 在输入旁边创建标签
【发布时间】:2019-07-01 10:52:29
【问题描述】:

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

我看到了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-labelledby 属性正常工作,我使用了一个 TextField

打印出 input 和 label 属性的内容给出:

//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。我得到的最接近的是带有标签属性的 div,它包装了输入,但什么也不显示。

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

【问题讨论】:

  • 我无法正确理解您要做什么以及有什么问题。但是here 是 TextField 的演示,在他们的文档上带有降档,这可能会对您有所帮助
  • @VaibhavVishal 谢谢,在查看这个特殊问题之前我已经看到了。我的假设是 getItemProps 会接受一个带有 label 属性的对象......但它不会。
  • 您已链接到 TextField 演示,但您看过降档演示吗? material-ui.com/demos/autocomplete/#downshift
  • @RyanCogswell 查看 Vaibhav 的评论和我的回复。两组演示我都看过。

标签: javascript reactjs material-ui downshift


【解决方案1】:

这里是 cmets 中提到的demo 的略微简化版本:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 2013-07-11
    • 2022-12-26
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2019-11-10
    相关资源
    最近更新 更多