日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React中的Refs屬性你來了解嗎_React

作者:橘貓吃不胖~ ? 更新時間: 2022-05-11 編程語言

1 介紹

react組件的三大屬性:

1.props屬性:封裝傳遞給組件的參數

2.state屬性:組件的狀態,當值發生改變后,重新渲染組件

3.refs屬性:

(1)通過該屬性可以去訪問DOM元素或render函數中的react元素(虛擬的DOM元素) ——DOM元素或render函數中的react元素的代理(句柄)

(2)本質是ReactDOM.render()函數返回的實例(組件實例或DOM節點)

Refs在計算機中稱為彈性文件系統。React中的Refs提供了一種方式,允許我們訪問DOM節點或在render方法中創建的React元素。本質為ReactDOM.render()返回的組件實例,如果是渲染組件則返回的是組件實例,如果渲染dom則返回的是具體的dom節點。

作用:Refs時React提供給我們安全訪問DOM元素或者某個組件實例的句柄。在類組件中,React將ref屬性中第一個參數作為DOM中的句柄。在函數組件中,React用hooks的api useRef也能獲得ref。

2 使用方法

2.1 createRef(版本>=React16.3)

一般在構造函數中將refs分配給實例屬性,以供組件的其他方法中使用。

1、對于html元素:可以獲取元素實例

示例代碼:

class Refs extends React.Component {
    constructor(props) {
        super(props);
        // 在構造函數中初始化一個ref,然后在return中就可以使用了
        this.myRef = React.createRef();
        console.log(this.myRef);
    }
    componentDidMount() { // 在render()函數執行完成后調用
        this.myRef.current.innerHTML = "橘貓吃不胖"; // this.myRef中有一個current屬性
    }
    render() {
        return (
            
{/*如果ref屬性被用于html,那么它的值就是底層DOM元素*/}
); } }

在這里插入圖片描述

2、可以和類組件進行綁定 —— 代表類組件的實例

示例代碼:

class Refs extends React.Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
    }
    componentDidMount() {
        // 在父組件中調用了子組件的方法
        this.myRef.current.change();
    }
    render() {
        return 
    }
}

class Children extends React.Component {
    change() {
        console.log("橘貓吃不胖變身");
    }
    render() {
        return 橘貓吃不胖
    }
}

2.2 回調Refs

React將在組件掛載時,會調用ref回調函數并傳入DOM怨怒是,當卸載時調用它并傳入null。早componentDidMount或componentDidUpdate觸發前,React會保證refs一定是最新的。

示例代碼:

class Refs extends React.Component {
    constructor(props) {
        super(props);
        this.targetRef = null;
        this.myRef = (e) => this.targetRef = e;
    }
    componentDidMount() {
        console.log("this.refs" + this.refs.container);
    }
    render() {
        return 
橘貓吃不胖
} }

2.3 String類型的Refs(已過時,不推薦使用)

示例代碼:

class Refs extends React.Component {
    constructor(props) {
        super(props);
        this.targetRef = null;
        this.myRef = (e) => this.targetRef = e;
    }
    componentDidMount() {
        console.log("this.refs" + this.refs.container);
    }
    render() {
        return 
橘貓吃不胖
} }

2.4 useRef(React Hooks)

function HookRef(props) {
    const inputElement = useRef();
    return (
        
) }

總結

原文鏈接:https://blog.csdn.net/m0_46612221/article/details/123360259

欄目分類
最近更新