ref useRef React.createRef React.forwardRef

react如何獲取真實(shí)DOM:useRef, React.CreateRef()

access DOM nodes directly within React:ref.current

Let’s say you want to change the value of an?<input>?element, but without using props or re-rendering the whole component.?They’re an excellent way to update part of a component without the need to re-render the entire thing.?


1. useRef

const {useRef} = React


const App=()=>{

????const buttonRef=useRef();

????return(

????<button

????????onClick={()=>{console.log(buttonRef.current);}}

????????ref={buttonRef} >

????????Special Button

????</button>

????);

}


2. React.createRef()

create a ref by calling?React.createRef()?and attaching a React element to it using the?ref?attribute on the element.

class Example extends React.Component {?

constructor(props) {?

????super(props)?

????this.exampleRef = React.createRef()?// Create the ref?

}?

render() {?

?return (?

?<div>?

? ? //這里是uncontrolled form

?????<input type="text" ref={this.exampleRef} />?// Call the ref with the `ref` attribute

</div>?

)?

}}


3.?Passing a callback function to ref

create a ref by passing a callback function to the?ref?attribute of a component.?

<input type="text" ref={element=>this.textInput=element}/>

The callback is used to store a reference to the DOM node in an instance property. When we want to make use of this reference, we access it using: this.textInput.value

When you make use of callback like we did above, React will call the ref callback with the DOM node when the component mounts, when the component un-mounts, it will call it with null.

class App extends React.Component {?

????state = { value: '' }

????handleSubmit = e => {?

????e.preventDefault();? ??

????this.setState({ value: this.textInput.value})??

};??

render() {? ??

????return (? ? ??

????<div>? ?

????????<h3>Value: {this.state.value}</h3>? ? ? ??

????????<form onSubmit={this.handleSubmit}>? ? ? ? ??

????????<input type="text" ref={element => this.textInput = element} />? ? ? ? ??

????????<button>Submit</button>? ? ? ??

????</form>? ? ??

</div>? ??

);? }}


4.?pass ref from a parent component to a child component using callbacks.

child:

const Input = props =>{

????return(

//This component is expecting?inputRef?props from its parent component which is then used to create a ref to the DOM node.

? ? ? ? <inputtype="text" ref={ props.inputRef }/>

????);

};

parent:

In the App component, we want to obtain the text that is entered in the input field (which is in the child component) so we can render it. The ref is created using a callback like we did in the first example of this section. The key lies in how we access the DOM of the input element in the Input component from the App component. If you look closely, we access it using?this.inputElement. So, when updating the state of value in the App component, we get the text that was entered in the input field using?this.inputElement.value.

class App extends React.Component{

????state={

????????value:""

????};

????handleSubmit=event=>{

????????this.setState({ value:this.inputElement.value });

????};

????render() {

????????return(

????????????<div>

????????????????<h3>Value: {this.state.value}</h3>

????????????????<Input inputRef={el=>(this.inputElement=el)}/>

????????????????<button onClick={this.handleSubmit}>Submit</button>

????</div>

);}}


5.?Forwarding a ref from one component to another

Ref forwarding is the technique of passing a ref from a component to a child component by making use of the?React.forwardRef()?method.

child:?

const Input=React.forwardRef((props,ref)=>(

????<inputtype="text"ref={ref}/>

));

parent:

class App extends React.Component{

????constructor(props) {

????????super(props)

????????this.inputRef=React.createRef();

????????this.state={value:''}

????}

????handleSubmit=e=>{

????????e.preventDefault();

????????this.setState({value:this.inputRef.current.value})

????};

????render() {

????????return(

????????????<div>

????????????????<h3>Value: {this.state.value}</h3>

????????????????<form onSubmit={this.handleSubmit}>

????????????????????<Input ref={this.inputRef}/>

????????????????????<button>Submit</button>

????????????????</form>

????????????</div>

);}}


uncontrolled form example: Using ref for form validation

class App extends React.Component {?

????constructor(props) {?

????????super(props);?

?????????this.username = React.createRef();?

?????????this.password = React.createRef();?

?????????this.state = {?

?????????????errors: []?

?????????};?

?}?

?????handleSubmit = (event) => {?

?????????event.preventDefault();?

?????????const username = this.username.current.value;?

?????????const password = this.password.current.value;?

?????????const errors = this.handleValidation(username, password);?

?????????if (errors.length > 0) {?

?????????????this.setState({ errors });?

?????????????return;?

?????????????}?

?????????????// Submit data?

?????};?

? ? handleValidation = (username,password) => {?

????????const errors = [];?

????????if (username.length === 0) { errors.push("Username cannot be empty"); }?

? ? ? ? if (password.length < 6) { errors.push("Password should be at least 6 characters long");}? ?

? ? ? ? ?return errors;??

????};??


render() {? ??

????const { errors } = this.state;? ??

????return (? ? ??

? ? <form onSubmit={this.handleSubmit}>? ? ? ? ??

????????{errors.map(error => <p key={error}>{error}</p>)}? ? ? ? ??

????????<input type="text" ref={this.username} />? ? ? ? ??

????????<input type="text" ref={this.password} />?

????????<button>Submit</button>? ? ? ? ?

?</form>? ? ??

);}}


訪問節(jié)點(diǎn)的情況


將節(jié)點(diǎn)綁定在this.input屬性上


dom api:focus


無狀態(tài)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市院仿,隨后出現(xiàn)的幾起案子秸抚,更是在濱河造成了極大的恐慌速和,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,743評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件剥汤,死亡現(xiàn)場(chǎng)離奇詭異颠放,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)吭敢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,296評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門碰凶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人鹿驼,你說我怎么就攤上這事欲低。” “怎么了畜晰?”我有些...
    開封第一講書人閱讀 157,285評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵砾莱,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我凄鼻,道長(zhǎng)腊瑟,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,485評(píng)論 1 283
  • 正文 為了忘掉前任块蚌,我火速辦了婚禮扫步,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘匈子。我一直安慰自己河胎,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,581評(píng)論 6 386
  • 文/花漫 我一把揭開白布虎敦。 她就那樣靜靜地躺著游岳,像睡著了一般。 火紅的嫁衣襯著肌膚如雪其徙。 梳的紋絲不亂的頭發(fā)上胚迫,一...
    開封第一講書人閱讀 49,821評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音唾那,去河邊找鬼访锻。 笑死,一個(gè)胖子當(dāng)著我的面吹牛闹获,可吹牛的內(nèi)容都是我干的期犬。 我是一名探鬼主播,決...
    沈念sama閱讀 38,960評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼避诽,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼龟虎!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起沙庐,我...
    開封第一講書人閱讀 37,719評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤鲤妥,失蹤者是張志新(化名)和其女友劉穎佳吞,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體棉安,經(jīng)...
    沈念sama閱讀 44,186評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡底扳,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,516評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了贡耽。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片花盐。...
    茶點(diǎn)故事閱讀 38,650評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖菇爪,靈堂內(nèi)的尸體忽然破棺而出算芯,到底是詐尸還是另有隱情,我是刑警寧澤凳宙,帶...
    沈念sama閱讀 34,329評(píng)論 4 330
  • 正文 年R本政府宣布熙揍,位于F島的核電站,受9級(jí)特大地震影響氏涩,放射性物質(zhì)發(fā)生泄漏届囚。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,936評(píng)論 3 313
  • 文/蒙蒙 一是尖、第九天 我趴在偏房一處隱蔽的房頂上張望意系。 院中可真熱鬧,春花似錦饺汹、人聲如沸蛔添。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,757評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)迎瞧。三九已至,卻和暖如春逸吵,著一層夾襖步出監(jiān)牢的瞬間凶硅,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,991評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工扫皱, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留足绅,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,370評(píng)論 2 360
  • 正文 我出身青樓韩脑,卻偏偏與公主長(zhǎng)得像氢妈,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子扰才,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,527評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容