1. Reset the keyboard focus to the designated button:
// 我们先在一个 class 组件的 JSX 中创建一个元素的 ref:
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();
}
Second, the parent component needs to set the focus on an element of its child component:
We can expose the DOM refs to the parent component by setting a special prop on the child component to pass the ref of the parent component to the DOM node of the child node.