通过 ref 可以获取到DOM元素 / 组件的实例对象
1. React.createRef方法(推荐使用)
2. ref=函数
3. ref=字符串(不推荐使用)
4. 注意:函数组件不能使用ref,要使用React.forwardRef()
例子
1. React.createRef方法(推荐使用)
this.inputRef = React.createRef()
<input ref={ this.username } />
输出元素的DOM对象:this.username.current
2. ref=函数
<input ref={ input => (this.username = input) } />
输出元素的DOM对象:this.username
3. ref=字符串(不推荐使用)
<input ref='username' />
输出元素的DOM对象:this.refs.username
4. 注意:函数组件不能使用ref,要使用React.forwardRef()
let TextInput = React.forwardRef((props, ref) => {
return <input ref={ref} />
})
例子:
需求:点击按钮让input文本获取焦点
input文本框以及让文本框获取焦点的方法定义在input组件中
在App组件中引入input组件,按钮定义在App组件中
关键API:React.createRef()
创建ref后,就可以通过current属性拿到实例
Input.js
// Input.js
import React, { Component } from 'react'
export default class Input extends Component {
constructor() {
super()
this.inputRef = React.createRef()
this.focusInput = this.focusInput.bind(this)
}
focusInput() {
this.inputRef.current.focus()
}
render() {
return (
<div>
<input type="text" ref={this.inputRef} />
</div>
)
}
}
App.js
// App.js
import React, { Component } from 'react'
import Input from './Input'
export default class App extends Component {
constructor() {
super()
this.InputComponentRef = React.createRef()
}
render() {
return (
<div>
<Input ref={this.InputComponentRef} />
<button onClick={() => this.InputComponentRef.current.focusInput()}>
button
</button>
</div>
)
}
}