实现跨层级的组件通信
在src中新建文件夹context? 新建文件index.tsx
里面写入
import React from "react";
export default React.createContext(10)
爷组件
引入
import NumContext from "../context"
import React, { Component } from 'react'
import Child1 from '../components/Child1'
import NumContext from "../context"
export default class UseContext extends Component {
render() {
return (
<div>
<NumContext.Provider value={{ num: 999 }}>
跨层级通信
<Child1></Child1>
</NumContext.Provider>
</div>
)
}
}
子组件
import React, { Component } from 'react'
import Child2 from './Child2'
export default class Child1 extends Component {
render() {
return (
<div>
子组件
<Child2></Child2>
</div>
)
}
}
孙组件
引入
import React, { useContext } from 'react'
import NContext from "../context";
import React, { useContext } from 'react'
import NContext from "../context";
export default function Child2() {
const context = useContext(NContext);
return (
<div>
我是孙组件
{context.num}
</div>
)
}
|