擷取焦點
- 前言
- 方式一:
-
- React.createRef()
- 方式二:
-
- 使用函數
前言
在React中,隻要props或state發生改變,則render()方法必定執行,即DOM會更新。然React更新DOM時,可能會導緻已經擷取焦點的元素失去焦點,故此時需要操作DOM,擷取焦點。
方式一:
React.createRef()
使用React.createRef()方法可以建立一個存儲dom的ref,當ref設定在元件上時,即可存儲該元素的dom引用。
// index.js
import React from 'react'
import CustomTextInput from './CustomTextInput'
class Parent extends React.Component {
constructor(props) {
super(props);
// 建立一個ref存儲dom元素
this.inputElement = React.createRef();
this.getFocus = this.getFocus.bind(this)
}
getFocus() {
this.inputElement.current.focus()
}
render() {
return (
<CustomTextInput
inputRef={this.inputElement}
inputGetFocus={this.getFocus}
/>
)
}
}
export default Parent
// CustomTextInput.js
import React from 'react'
const CustomTextInput = (props) => {
return (
<React.Fragment>
<input
type="text"
ref={props.inputRef}
/>
<button onClick={props.inputGetFocus}>擷取焦點</button>
</React.Fragment>
)
}
export default CustomTextInput
方式二:
使用函數
// index.js
import React from 'react'
import CustomTextInput from './CustomTextInput'
class Parent extends React.Component {
constructor(props) {
super(props);
this.getInputElement = this.getInputElement.bind(this)
this.getFocus = this.getFocus.bind(this)
}
getFocus() {
this.inputElement.focus()
}
getInputElement(el) {
this.inputElement = el
}
render() {
return (
<CustomTextInput
inputRef={this.getInputElement}
inputGetFocus={this.getFocus}
/>
)
}
}
export default Parent