【发布时间】:2017-03-01 04:12:40
【问题描述】:
我想实现自动对焦,但我无法通过不以编程方式设置 autofocus=true 来从标记中实现它。有什么帮助吗?
【问题讨论】:
标签: reactjs material-ui
我想实现自动对焦,但我无法通过不以编程方式设置 autofocus=true 来从标记中实现它。有什么帮助吗?
【问题讨论】:
标签: reactjs material-ui
你可以这样做:<TextField autoFocus></TextField>。
更多信息:https://facebook.github.io/react/docs/tags-and-attributes.html#html-attributes。
【讨论】:
由于某种原因,这对我不起作用(可能是因为它位于顶层组件挂载时不可见的组件中)。我必须做一些更复杂的事情才能让它工作:
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。
【讨论】:
我只是简单地将输入的 ref 放入状态
<TextInput inputRef={el => { this.setState({form: el}) }}/>
然后您可以将焦点设置到任何地方的输入。
this.state.form.focus()
【讨论】: