ref的三種使用方式與forwardRef
一、ref的三種使用方式
源碼前言
function Component (props, context,updater)
Component.prototype.setState = function(partialState,callback) {
…
this.updater.enqueueSetState(this,partialState,callback,)
}
updater.enqueueSetState是在reactDOM里實現(xiàn)的。
Component 核心是一樣的,
更新的流程不同
類的繼承中初始化定義函數(shù)的時候,在他的原型上還可以使用傳遞進來的參數(shù)嗎?源碼上是可以的,回家試一試。
React中ref的三種使用方式:
應(yīng)用:1.this.refs.stringRef.textContent="string ref got"2.this.methodRef.textContent="method ref got"3.//先創(chuàng)建一個ref對象exportdefaultclassCompextendsReact.Component{super();this.objRef=React.createRef();}//this.objRef.current.textContent="obj ref got"<p ref={this.objRef}>asdf</p>
//string ref? ? 想要獲取的那個節(jié)點的props上面使用ref屬性傳入一個字符串,
react在完成這個節(jié)點的渲染之后,會在this.ref上面掛載string對應(yīng)的key
也就是stringRef(如果是DOM節(jié)點就會對應(yīng)DOM的實例,如果是子組件就對應(yīng)組件的實例classComponent)
>但是如果是function Component呢,正常來說是會失敗的,因為function Component是
>沒有實例的,那怎么解決呢,后面的forward-ref(讓我們在function Component使用ref也不會出錯)
<p ref="string">asdf</p>下一個大版本(React17)會廢棄,ref會傳入一個字符串,然后
//function? ? 參數(shù)ele是節(jié)點對應(yīng)的實例,DOM節(jié)點的實例,或者組件的實例
<p ref={ele=>(this.methodRef=ele)}></p>
//React提供給我們的一個API:首先在class Component中使用
this.objRef = React.createRef() 創(chuàng)建一個對象相當于//{current:null }
<p ref = {this.objRef}>asdf</p>
//然后把創(chuàng)建的對象(通過ref={}形式)傳給某一個節(jié)點,就會把某個對象
的實例掛載到,current這個屬性上面。
二、forwardRef
假設(shè):當時純函數(shù)組件的時候,沒有實例對象,就不能使用獲得對應(yīng)的實例對象,follow meimportReact,{Component}from'react'cosntTargetComponent=(props)=>{<input type="text"/>}exportdefaultclassCompextendsComponent{constructor(){super();this.ref=React.createRef();//創(chuàng)建一個對象? { current : null }}componentDidMount(){this.ref.current.value="ref get input"}render(){return<TargetComponent ref={this.ref}/>}}
importReactfrom'react'constTargetComponent=React.forwardRef(()=>(<input type="text"ref={ref}/>))exportdefaultclassCompextendsReact.Component{constructor(){super();this.ref=React.createRef();}componentDidMount(){this.ref.current.value="ref get input"}render(){return<TargetComponent ref={this.ref}/>}}