日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

React ref的转发

發布時間:2024/7/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 React ref的转发 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在前面學習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;

總結

以上是生活随笔為你收集整理的React ref的转发的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。