虽然这种方式现在很少用了,但还是了解一下
1.首先是类组件
import React, { Component } from 'react'
const UserContext = React.createContext({
name: 'aaa'
})
class Header extends Component {
render () {
// console.log(this.context);
return (
<div>
<h2>用户昵称:{this.context.name}</h2>
</div>
)
}
}
Header.contextType = UserContext
function Profile (props) {
return (
<div>
<Header />
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
)
}
export default class App extends Component {
constructor() {
super()
this.state = {
name: 'code-v'
}
}
render () {
return (
<div>
<UserContext.Provider value={this.state}>
<Profile />
</UserContext.Provider>
</div>
)
}
}
2.函数组件
import React, { Component } from 'react'
const UserContext = React.createContext({
name: 'aaa'
})
function Header () {
return (
<UserContext.Consumer>
{
value => {
return (
<div>
<h2>用户昵称:{value.name}</h2>
</div>
)
}
}
</UserContext.Consumer>
)
}
function Profile (props) {
return (
<div>
<Header />
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
)
}
export default class App extends Component {
constructor() {
super()
this.state = {
name: 'code-v'
}
}
render () {
return (
<div>
<UserContext.Provider value={this.state}>
<Profile />
</UserContext.Provider>
</div>
)
}
}