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>
)
}
參考鏈接: