【问题标题】:Autofocus TextField using React Material-UI使用 React Material-UI 自动对焦 TextField
【发布时间】:2017-03-01 04:12:40
【问题描述】:

我用Material-UI TextField

我想实现自动对焦,但我无法通过不以编程方式设置 autofocus=true 来从标记中实现它。有什么帮助吗?

【问题讨论】:

标签: reactjs material-ui


【解决方案1】:

你可以这样做:<TextField autoFocus></TextField>

更多信息:https://facebook.github.io/react/docs/tags-and-attributes.html#html-attributes

【讨论】:

【解决方案2】:

由于某种原因,这对我不起作用(可能是因为它位于顶层组件挂载时不可见的组件中)。我必须做一些更复杂的事情才能让它工作:

const focusUsernameInputField = input => {
  if (input) {
    setTimeout(() => {input.focus()}, 100);
  }
};

return (
  <TextField
    hintText="Username"
    floatingLabelText="Username"
    ref={focusUsernameInputField}
  />
)

欲了解更多信息,请参阅https://github.com/callemall/material-ui/issues/1594

【讨论】:

  • "...该元素必须可见才能获得焦点。以下类型的元素如果未禁用,则可以获得焦点:输入、选择、文本区域、按钮和对象。锚点是可聚焦的如果它们具有 href 或 tabindex 属性。area 元素是可聚焦的,如果它们位于命名地图内,具有 href 属性,并且有使用地图的可见图像。所有其他元素仅基于它们的 tabindex 属性和可见性是可聚焦的。 ":来自api.jqueryui.com/focusable-selector
【解决方案3】:

我只是简单地将输入的 ref 放入状态

&lt;TextInput inputRef={el =&gt; { this.setState({form: el}) }}/&gt;

然后您可以将焦点设置到任何地方的输入。

this.state.form.focus()

【讨论】:

    猜你喜欢
    • 2019-02-15
    • 1970-01-01
    • 2018-02-08
    • 2019-01-23
    • 2020-03-13
    • 1970-01-01
    • 2019-08-30
    • 2021-09-05
    • 2016-12-21
    相关资源
    最近更新 更多