您好,登錄后才能下訂單哦!
在React中使用refs可以通過兩種方式來獲取DOM元素或者組件的引用:
createRef
方法創(chuàng)建ref對象:import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
this.myRef.current.focus();
}
render() {
return <input ref={this.myRef} />;
}
}
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.inputRef = null;
}
componentDidMount() {
this.inputRef.focus();
}
setInputRef = (element) => {
this.inputRef = element;
}
render() {
return <input ref={this.setInputRef} />;
}
}
在上面的例子中,我們創(chuàng)建了一個ref對象myRef
,然后在componentDidMount
生命周期鉤子中使用this.myRef.current
來訪問DOM元素。另外,也可以使用回調(diào)函數(shù)的方式來創(chuàng)建ref,將ref賦值給一個類的實例變量,然后在需要的時候直接調(diào)用該實例變量即可。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。