跨级组件通信
类组件
contextType.js
import React from 'react';
export default React.createContext({curInfo: {name: 'll', age:5}})
import React, {Component} from 'react';
import { Button, Flex } from 'antd';
import CurContextType from './contextType';
import 'antd/dist/reset.css';
import Parent from './classCom/parent'
class App extends Component {
constructor() {
super()
this.state = {
curInfo:{
name: 'zhangsan',
age: 9
}
}
}
render() {
const { curInfo } = this.state
return <div>
<Button type="primary" onClick={this.setAge}>新增一岁</Button>
<CurContextType.Provider value={{curInfo}}>
<h1>main.js</h1>
<div>姓名:{curInfo.name} 年纪:{curInfo.age}</div>
<Parent />
</CurContextType.Provider>
</div>
}
}
import React, {Component} from 'react';
import CurContextType from '../contextType'
import Son from './son'
class Parent extends Component {
static contextType = CurContextType
constructor(props) {
super(props)
this.state = {}
}
render() {
console.log(this.context, '0000' )
return <div>
<div>我的父亲是{this.context?.curInfo?.name},我的父亲的年纪是{this.context?.curInfo?.age}</div>
<Son />
</div>
}
}
export default Parent
class Son extends Component {
constructor(props) {
super(props)
this.state = {}
}
static contextType = CurContextType
render() {
console.log(this.context, '0000' )
return <div>
<div>我的祖父是{this.context?.curInfo?.name},我的祖父的年纪是{this.context?.curInfo?.age}</div>
234
</div>
}
}
export default Son
<CurContextType.Consumer>
{ state =><div>...</div>
</CurContextType.Consumer>
函数组件
import React, {useState} from 'react';
import { Button, Flex } from 'antd';
import CurContextType from './contextType';
import 'antd/dist/reset.css';
import Parent from './classCom/parent'
function App() {
const [curInfo, setInfo] = useState({name: 'll', age: 5})
const setAge = () => {
setInfo({...curInfo, age: curInfo.age+1})
}
return (
<div>
<Button type="primary" onClick={setAge}>新增一岁</Button>
<CurContextType.Provider value={{curInfo,setAge}}>
<h1>main.js</h1>
<div>姓名:{curInfo.name} 年纪:{curInfo.age}</div>
<Parent />
</CurContextType.Provider>
</div>
);
}
import CurContextType from '../contextType'
import Son from './son'
export default function Parent(props) {
return <CurContextType.Consumer>
{
(context) => <div>
<div>我的父亲是{context?.curInfo?.name},我的父亲的年纪是{context?.curInfo?.age}</div>
<Son />
</div>
}
</CurContextType.Consumer>
}
import { useContext } from "react"
import CurContextType from '../contextType'
export default function Son(props) {
const context = useContext(CurContextType)
return <div >
<div>我的祖父是{context?.curInfo?.name},我的祖父的年纪是{context?.curInfo?.age}</div>
234
</div >
}