reactjs - 如何将 Material UI 文本字段集中在按钮单击上?
问题描述
单击按钮后如何聚焦文本字段。我尝试使用 autoFocus,但没有成功:示例沙箱
<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-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 的 ref 更新为 inputRef。
推荐阅读
- r - 如何调整用ggplot2制作的图形中的所有线宽?
- asp.net - 初学者关于WebApi和路由的问题
- c# - 启动进程以显示浏览器后停止/终止 .net 核心 Web 应用程序进程的正确方法是什么
- python-3.x - 如何从python中的名称中删除字母首字母?
- c# - 如何在每个查询或命令中执行 Post Handler
- bitbucket - Bitbucket PR 土地坩埚限制
- spring - 调用 save() 时无法删除 JPA 中的集合行
- python - Flask - 使用来自 API 端点的参数运行代码
- ios - 如何在 WatchOS 中构建 PagerView
- python - 我可以使用 HTTP 将 Python GUI 连接到网站吗?