Refs介绍
React 支持一种非常特殊的属性 Ref ,你可以用来绑定到 render() 输出的任何组件上。这个特殊的属性允许你引用 render() 返回的相应的支撑实例( backing instance )。这样就可以确保在任何时间总是拿到正确的实例。
// 示例
<input ref="myInput" />
// 获取
let input = this.refs.myInput;
let inputValue = input.value;
let inputRect = input.getBoundingClientRect();
Refs的主要用途
- 做一些动画的交互
- 媒体控件的播放
- 获取焦点、获取文本等
Refs的两种创建方法
- 使用React.createRef() API
import React from 'react';
export default class RefApp extends React.Component {
constructor(props) {
super(props);
this.input = React.createRef(); // 创建一个 ref 来存储 input 的 DOM 元素
this.copy= this.copy.bind(this);
}
copy() {
console.log(this.input) // 访问创建的refs
this.input.current.select(); // 使用current可以获取到当前元素
}
render() {
return (
<div>
<input ref={this.input} type="text" ></input>
<button onClick={this.copy.bind(this)} >点击复制内容</button>
</div>
)
}
}
- 通过回调Refs获取dom
ref为回调函数
import React from 'react';
export default class RefApp extends React.Component{
constructor(props){
super(props);
this.copy= this.copy.bind(this);
this.input = null;
}
//对文本内容进行复制
copy(){
this.input.select();
}
render(){
return (
<div>
{/* 一、ref可以是回调函数,此时参数e即为该dom元素本身,将它绑定到对象属性input中 */}
<input ref={e=>this.input=e} type="text" ></input>
<button onClick={this.copy} >点击复制内容</button>
</div>
)
}
}
ref为字符串(不推荐使用)
copy(){
console.log(this.refs);
this.refs.inputEle.select();
}
render(){
return (
<div>
{/* 二、ref为字符串,通过组件对象下的refs属性获取 */}
<input ref="inputEle" type="text" ></input>
<button onClick={this.copy} >点击复制内容</button>
</div>
)
}
父组件通过refs获取子组件中的dom
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}
在上面的例子中,Parent 将它的 ref 回调作为一个特殊的 inputRef 传递给CustomTextInput,然后 CustomTextInput 通过ref 属性将其传递给 input。最终,Parent 中的 this.inputElement将被设置为与 CustomTextInput中的input元素相对应的 DOM 节点。