在前面学习ref时讲过,ref不能应用于函数式组件:
因为函数式组件没有实例,所以不能获取到对应的组件对象
但是,在开发中我们可能想要获取函数式组件中某个元素的DOM,这个时候我们应该如何操作呢?
- 方式一:直接传入ref属性(错误的做法)
- 方式二:通过forwardRef高阶函数;
import React, {PureComponent, createRef, forwardRef} from 'react';
class Home extends PureComponent{render() {return <h2>Home</h2>}
}
/*function Profile(props) {return <h2>Profile</h2>
}*/
const Profile = forwardRef(function Profile(props, ref) {return <h2 ref={ref}>Profile</h2>
})
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</h2><Home ref={this.homeRef} /><Profile ref={this.profileRef} /><button onClick={e => this.printRef()}>打印ref</button></div>);}printRef () {console.log(this.titleRef.current)console.log(this.homeRef.current)console.log(this.profileRef.current)}
}
export default App;