react中的context是什么呢
Context 通過組件樹提供了?個(gè)傳遞數(shù)據(jù)的?法,從?避免了在每?個(gè)層級(jí)?動(dòng)的傳遞 props 屬性郁妈。
?檔也沒具體給出context到底是什么涡上,?是告訴我們context能?什么趾断,也就是說拒名,如果我們不想通過props實(shí)現(xiàn)組件樹的逐層傳遞
數(shù)據(jù)吩愧,則可以使?context實(shí)現(xiàn)跨層級(jí)進(jìn)?數(shù)據(jù)傳遞!
創(chuàng)建Context,
ContextData.jsx ,通過 Provider 進(jìn)行數(shù)據(jù)傳遞
import React, { Component } from 'react'
// 創(chuàng)建 Context 并導(dǎo)出
export const Context = React.createContext()
export class ContextData extends Component {
constructor(props) {
super(props)
this.state = {
users: [
{
name: '小明',
age: 18,
sex: '男',
},
{
name: '小紅',
age: 16,
sex: '女',
},
{
name: '小王',
age: 20,
sex: '男',
},
],
}
}
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
)
}
}
Middle.jsx
import React from 'react'
import Foo from './Foo'
import Bar from './Bar'
function Middle() {
return (
<div>
<Foo></Foo>
<Bar></Bar>
</div>
)
}
export default Middle
Foo.jsx, 類組件
方式一: 通過 Consumer 里面{放一個(gè)函數(shù)} 來獲得 Context 的數(shù)據(jù)
import React, { Component } from 'react'
import {Context} from './ContextData'
export class Foo extends Component {
render() {
return (
<Context.Consumer>
{appContext=><div>Foo:{JSON.stringify(appContext.users[0])}</div>}
</Context.Consumer>
)
}
}
export default Foo
Bar.jsx 函數(shù)式組件
方式二: 通過 useContext 傳入創(chuàng)建的 Context
import React from 'react'
import {Context} from './ContextData'
function Bar() {
const appContext = React.useContext(Context)
return (
<div>
<p>Bar: {JSON.stringify(appContext.users[1])}</p>
</div>
)
}
export default Bar
Baz.jsx 類組件
方式三: 通過靜態(tài)屬性
static contextType = Context,
const appContext = this.context;
import React, { Component } from 'react'
import {Context} from './ContextData'
export default class Baz extends Component {
static contextType = Context
render() {
const appContext = this.context;
return (
<div>
{/* <p>這是一個(gè)懶加載...</p> */}
Baz: {JSON.stringify(appContext.users[2])}
</div>
)
}
}
瀏覽器顯示結(jié)果