天天看點

React-元件-Ref轉發

擷取函數式元件中的元素

如果要擷取的不是函數式元件本身, 而是想擷取函數式元件中的某個元素,那麼我們可以使用 ​

​Ref 轉發​

​ 來擷取。

在之前的文章當中示範了通過 Ref 擷取函數式元件,但是在控制台報了一個警告,警告的内容如下:

Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

意思就是告訴我們函數式元件不能夠使用 Ref 你可能是想使用 React.forwardRef(),React.forwardRef() 是什麼呢,它是一個高階元件,是一個高階函數,我們可以通過它來建立一個元件,通過它建立出來的元件就可以把外界設定的 Ref 傳遞給函數式元件的内部,然後在函數式内部通過這個傳遞過來的 Ref 進行擷取函數式元件當中的元素即可。不管三七二十一,現在直接上代碼:

import React from "react";

const About = React.forwardRef((props, myRef) => {
    return (
        <div ref={myRef}>
            <p>我是段落</p>
            <span>我是span</span>
        </div>
    )
});

class App extends React.PureComponent {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
    }

    render() {
        return (
            <div>
                <About ref={this.myRef}/>
                <button onClick={() => {
                    this.btnClick()
                }}>APP按鈕
                </button>
            </div>
        )
    }

    btnClick() {
        console.log(this.myRef.current);
    }
}

export default App;      
React-元件-Ref轉發