您好,登錄后才能下訂單哦!
今天小編給大家分享一下React Context如何使用的相關(guān)知識點,內(nèi)容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
一種React組件間通信方式, 常用于【祖組件】與【后代組件】間通信
import React, { Component } from "react"; import "./index.css"; export default class A extends Component { state = { username: "tom", age: 18 }; render() { const { username, age } = this.state; return ( <div className="parent"> <h4>我是A組件</h4> <h5>我的用戶名是:{username}</h5> <B username={username} age={age}></B> </div> ); } } class B extends Component { render() { console.log(this.props); const { username, age } = this.props; return ( <div className="child"> <h4>我是B組件</h4> <C username={username} age={age} /> </div> ); } } function C(props) { const { username, age } = props; return ( <div className="grand"> <h4>我是C組件</h4> <h5> 我從A組件接收到的用戶名:{username},年齡是{age} </h5> </div> ); }
這里C組件用了下函數(shù)式組件的寫法
但是這種寫法有很多的不太好的地方,如果層級再深一點呢,傳的值再多一點呢??隙〞泻芏嗟闹貜?fù)代碼出現(xiàn),而且我只想要祖組件和孫組件通信,這樣寫的話其實是每個組件都在通信了的。
Context的就可以挺好的適用于這種場景
創(chuàng)建Context容器對象:
const XxxContext = React.createContext()
2) 渲染子組時,外面包裹xxxContext.Provider, 通過value屬性給后代組件傳遞數(shù)據(jù):
<xxxContext.Provider value={數(shù)據(jù)}>
子組件
</xxxContext.Provider>
3) 后代組件讀取數(shù)據(jù):
//第一種方式:僅適用于類組件
static contextType = xxxContext // 聲明接收context
this.context // 讀取context中的value數(shù)據(jù)
//第二種方式: 函數(shù)組件與類組件都可以
<xxxContext.Consumer>
{
value => ( // value就是context中的value數(shù)據(jù)
要顯示的內(nèi)容
)
}
</xxxContext.Consumer>
上代碼
import React, { Component } from "react"; import "./index.css"; //創(chuàng)建Context對象 const MyContext = React.createContext(); const { Provider, Consumer } = MyContext; export default class A extends Component { state = { username: "tom", age: 18 }; render() { const { username, age } = this.state; return ( <div className="parent"> <h4>我是A組件</h4> <h5>我的用戶名是:{username}</h5> //如果傳的只有一個值例如username,應(yīng)該式value={username},后面就是直接獲取了,不需要再屬性名取值了 <Provider value={{ username, age }}> <B /> </Provider> </div> ); } } class B extends Component { render() { return ( <div className="child"> <h4>我是B組件</h4> <C/> </div> ); } } class C extends Component { //聲明接收context static contextType = MyContext render() { const {username,age} = this.context return ( <div className="grand"> <h4>我是C組件</h4> <h5>我從A組件接收到的用戶名:{username},年齡是{age}</h5> </div> ) } } // function C() { // return ( // <div className="grand"> // <h4>我是C組件</h4> // <h5> // 我從A組件接收到的用戶名: // {/* <Consumer>{(value) => `${value.username},年齡是${value.age}`}</Consumer> */} // </h5> // </div> // ); // }
以上就是“React Context如何使用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。