import React from 'react'
export default class RefUse extends React.Component{
constructor(props){
super(props)
this.objRef = React.createRef() //創建對象,注意獲取組件或dom節點時,其掛載在該對象的current屬性下,即this.objRef.current
this.state = {
}
}
componentDidMount(){
setTimeout(()=>{
this.refs.stringRef.textContent = 'update one'
console.log(this.methodRef)
this.methodRef.textContent = 'update two'
this.objRef.current.textContent = 'UPDATE THREE'
},3000)
}
render(){
return <div style={{textAlign:'center'}} >
<h4>ref的三種使用方式(用來獲取dom和組件對象)</h4>
<p ref="stringRef" >one</p> //字符串形式
<p ref={ele=>this.methodRef = ele}>two</p> //函數形式
<div ref={this.objRef}>three</div> //對象形式
</div>
}
}
react中ref的三種使用方式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.