组件A:类组件,Provider,create了一个ComplextContext
import ...
import React from 'react'
import { createContext } from 'react'
const ComplexContext = React.createContext('defaultValue')
class A extends React.Component{
const data1 = {...}
const data2 = [...]
const data3 = '...'
render(){
return(
<ComplexContext.Provider value={
...data1, data2, data3
}>
{children}
</ComplexContext.Provider>
)
}
}
export default A
组件B:函数组件,Consumer, 使用A中的ComplexContext
import ...
import contextProvider from 'url of A'
import { useContext } from 'react'
function B(){
const context = useContext(contextProvider)
console.log(context)
}
组件C:类组件,consumer,使用A中的ComplexContext
import ...
import contextProvider from 'url of A'
class C extends React.Component {
componentDidMount() {
let value = this.context;
/* 在组件挂载完成后,使用 MyContext 组件的值来执行一些有副作用的操作 */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* 基于 A 组件的值进行渲染 */
}
}
C.contextType = contextProvider;
入口文件App.js
import ProviderA from 'url of A'
import B from 'url of B'
import C from 'url of C'
function App() {
return (
<ProviderA>
<B/>
<C/>
<ProviderA>
)
}