用DOM元素的Refs在React中设置焦点
import React from 'react'
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// 创造一个 textInput DOM 元素的 ref
this.textInput = React.createRef();
}
render() {
// 使用 `ref` 回调函数以在实例的一个变量中存储文本输入 DOM 元素
//(比如,this.textInput)。
return (
<input
type="text"
ref={this.textInput}
/>
);
}
}
// 在需要时于其他地方把焦点设置在这个组件上
focus() {
// 使用原始的 DOM API 显式地聚焦在 text input 上
// 注意:我们通过访问 “current” 来获得 DOM 节点
this.textInput.current.focus();
}