react-hooks: useContext

React的useContext應(yīng)用場景:

如果需要在組件之間共享狀態(tài),可以使用useContext()

舉個??:

場景:現(xiàn)有兩個組件Navbar和Messages,希望他們之間共享狀態(tài)。

<div className="test">
    <Navbar />
    <Messages />
</div>
使用方法如下:

一、在兩個組件的父組件上使用React的Context API,及在組件外部建立一個Context。

const TestContext = React.createContext({});
  • 父組件封裝代碼如下:
    TestContext.Provider提供了一個Context對象,這個對象是可以被子組件共享的。
import React from "react";
const TestContext= React.createContext({});
<TestContext.Provider 
    value={{
        username: 'superawesome',
    }}
>
    <div className="test">
        <Navbar />
        <Messages />
    </div>
<TestContext.Provider/>
  • Navbar組件代碼如下(Message組件的代碼也類似):
    useContext()鉤子函數(shù)用來引入Context對象,從中獲取username屬性。
import React, { useContext } from "react";
const Navbar = () => {
    const { username } = useContext(TestContext);
    return (
        <div className="navbar">
            <p>{username}</p>
        </div>
    )
}

??????擴(kuò)展知識:Navbar組件訪問context的另一種方式:
組件引入TestContext并調(diào)用context,使用TestContext.Consumer(消費(fèi)者)

import TestContext from "父組件";
const Navbar = () => {
    return (
        <TestContext.Consumer>
            {
                    context => {
                      return (
                        <div> {context.useName} </div>
                      )
                    }
                }
          </TestContext.Consumer>
    )
}

參考鏈接:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容