ref的使用
在react的开发模式中,通常情况下不需要、也不建议直接操作DOM,但是在某些特殊的情况下,确实需要获取到DOM进行某些操作,那么如何通过创建ref来获取对应的DOM元素呢?目前有三种方式:
import React, { PureComponent, createRef, Component } from 'react';
class Counter extends PureComponent {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
render() {
return (
<div>
<h2>当前计数: {this.state.counter}</h2>
<button onClick={e => this.increment()}>+1</button>
</div>
)
}
increment() {
this.setState({
counter: this.state.counter + 1
})
}
}
export default class App extends PureComponent {
constructor(props) {
super(props);
this.titleRef = createRef();
this.counterRef = createRef();
this.titleEl = null;
}
render() {
return (
<div>
{/* <h2 ref=字符串/对象/函数>Hello React</h2> */}
<h2 ref="titleRef">Hello React</h2>
{/* 目前React推荐的方式:传入对象 */}
<h2 ref={this.titleRef}>Hello React</h2>
{/* 回调函数的方式 */}
<h2 ref={arg => this.titleEl = arg}>Hello React</h2>
<button onClick={e => this.changeText()}>改变文本</button>
<hr/>
<Counter ref={this.counterRef}/>
<button onClick={e => this.appBtnClick()}>App按钮</button>
</div>
)
}
changeText() {
// 1.使用方式一: 字符串(不推荐, 后续的更新会删除)
this.refs.titleRef.innerHTML = "Hello Coderwhy";
// 2.使用方式二: 对象方式
this.titleRef.current.innerHTML = "Hello JavaScript";
// 3.使用方式三: 回调函数方式
this.titleEl.innerHTML = "Hello TypeScript";
}
appBtnClick() {
//我们通过ref获取到子组件,因此在这里便可以直接拿到子组件的方法和数据了
this.counterRef.current.increment();
}
}
ref的转发
我们都知道ref是不能应用于函数式组件的,因为函数式组件不能实例化,所以不能获取到对应的组件对象,但是在开发中我们如果还是想要获取函数式组件中某个元素的DOM呢?通过forwardRef高阶函数进行一个ref的转发,示例代码如下:
import React, { PureComponent, createRef, forwardRef } from 'react';
class Home extends PureComponent {
render() {
return <h2>Home</h2>
}
}
// 高阶组件forwardRef
const Profile = forwardRef(
function (props, ref) {
return <p ref={ref}>Profile</p>
}
)
export default class App extends PureComponent {
constructor(props) {
super(props);
this.titleRef = createRef();
this.homeRef = createRef();
this.profileRef = createRef();
}
render() {
return (
<div>
<h2 ref={this.titleRef}>Hello World</h2>
<Home ref={this.homeRef}/>
<Profile ref={this.profileRef} name={"why"}/>
<button onClick={e => this.printRef()}>打印ref</button>
</div>
)
}
printRef() {
console.log(this.titleRef.current);
console.log(this.homeRef.current);
console.log(this.profileRef.current);
}
}