在react中,可以使用refs来访问dom,或者在render中创建react对象。
使用refs可以:
1.做一些动画的交互
2.媒体控件的播放
3.获取焦点、获取文本
等等
使用refs的方式有两种,一种是使用React.createRef() API,另一种是使用 回调形式的refs。
第一种方式,使用React.createRef() API
import React, { Component } from 'react'
export default class App extends React.Component {
constructor(props) {
super(props);
// 创建一个 ref 来存储 textInput 的 DOM 元素
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// 直接使用原生 API 使 text 输入框获得焦点
// 通过 "current" 来访问 DOM 节点
this.textInput.current.focus();
console.log(this.textInput.current);//这边输出input的dom对象
}
render() {
// 把 <input> ref 关联到
// 构造器里创建的 `textInput` 上
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="点击我获取焦点"
onClick={this.focusTextInput}
/>
</div>
);
}
}
第二种是回调 Refs,React 将在组件挂载时,会调用 ref 回调函数并传入 DOM 元素,当卸载时调用它并传入 null。在 componentDidMount 或 componentDidUpdate 触发前,React 会保证 refs 一定是最新的。
import React, { Component } from 'react'
export default class App extends React.Component {
constructor(props) {
super(props);
// 创建一个 ref 来存储 textInput 的 DOM 元素
this.textInput = null;
this.setTextInputRef = element => {
this.textInput = element;
};
this.focusTextInput = () => {
// 使用原生 DOM API 使 text 输入框获得焦点
if (this.textInput) this.textInput.focus();
};
}
componentDidMount() {
// 组件挂载后,让文本框自动获得焦点
this.focusTextInput();
}
render() {
// 使用 `ref` 的回调函数将 text 输入框 DOM 节点的引用存储到 React
// 实例上(比如 this.textInput)
return (
<div>
<input
type="text"
ref={this.setTextInputRef}
/>
<input
type="button"
value="点击我获取焦点"
onClick={this.focusTextInput}
/>
</div>
);
}
}