如何将Material UI Textfield集中在按钮单击上? [英] How to focus a Material UI Textfield on button click?
本文介绍了如何将Material UI Textfield集中在按钮单击上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在单击按钮后聚焦文本字段.我尝试使用autoFocus,但无法解决:沙箱示例
How to focus a Textfield after clicking a button. I tried to use autoFocus but it did not work out: Example sandbox
<div>
<button onclick={() => this.setState({ focus: true })}>
Click to focus Textfield
</button>
<br />
<TextField
label="My Textfield"
id="mui-theme-provider-input"
autoFocus={this.state.focus}
/>
</div>
推荐答案
您需要使用ref,请参见 https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a- dom元素
You need to use a ref, see https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<button onClick={this.focusTextInput}>
Click to focus Textfield
</button>
<br />
<TextField
label="My Textfield"
id="mui-theme-provider-input"
inputRef={this.textInput}
/>
</div>
);
}
}
已将Material-UI v3.6.1.的引用更新为inputRef.
Updated ref to inputRef for Material-UI v3.6.1.
这篇关于如何将Material UI Textfield集中在按钮单击上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文