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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

24 React.createRef()用法细节分析

發布時間:2023/12/10 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 24 React.createRef()用法细节分析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
  • 通過React.createRef → ref對象
  • 通過元素的ref屬性可以附加到React元素上
  • 一般通過構造器中給this的屬性賦值一個ref,方便整個組件使用
  • ref只要傳遞到react元素中,就可以利用ref的current屬性訪問到該真實DOM節點
  • ref在componentDidMount和componentDidUpdate觸發前更新

current里是null的現象

  • 由于打印時,this.modalRef才剛剛聲明,current是null,但是current是個引用值,展開時訪問的是最后的結果
class Modal extends React.Component {constructor(props) {super(props)this.modalRef = React.createRef()console.log('剛創建時', this.modalRef)}componentDidMount() {console.log('componentDidMount', this.modalRef)}componentDidUpdate() {console.log('componentDidUpdate', this.modalRef)}render() {return (<divref={this.modalRef}style={{width: '300px',border: '1px solid #000',display: this.props.toOpen ? 'block' : 'none'}}><h1>This is a Modal</h1><p>This is a super Modal</p></div>)} }

ref有不同的使用方式

  • ref放在html元素上 → current: 真實DOM
  • ref放在class組價上 → current: 組件實例
  • ref放在函數組件(沒有實例)→ 無法附加到組件上
class App extends React.Component {constructor(props) {super(props)this.refInApp = React.createRef()}state = {toOpen: false,}componentDidMount() {console.log('【APP】componentDidMount', this.refInApp)}changeStatus = (toOpen) => {this.setState({toOpen})}render() {return (<><Modal toOpen={this.state.toOpen} ref={this.refInApp} /><button onClick={() => this.changeStatus(true)}>打開</button><button onClick={() => this.changeStatus(false)}>關閉</button></>)} }

函數組件使用hooks獲取dom實例

function Test() {const divRef = React.useRef(null)React.useEffect(() => {console.log('函數組件使用hooks獲取ref', divRef)}, [])return (<div ref={divRef}>Test函數組件</div>) }

  • 若試圖在函數組價上傳ref屬性會告警
<Test ref={this.refInApp} />

總結

以上是生活随笔為你收集整理的24 React.createRef()用法细节分析的全部內容,希望文章能夠幫你解決所遇到的問題。

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