使用React Material-UI自动对焦TextField

时间:2016-10-19 13:26:57

标签: reactjs material-ui

我使用Material-UI TextField

我想实现自动对焦,我无法通过以编程方式设置autofocus=true来找到通过标记执行此操作的方法。有什么帮助吗?

3 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:3)

由于某些原因,这对我不起作用(可能是因为它在一个组件中,当顶级组件安装时不可见)。为了让它发挥作用,我不得不做一些更复杂的事情:

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

答案 2 :(得分:0)

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

<TextInput inputRef={el => { this.setState({form: el}) }}/>

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

this.state.form.focus()