在之前我们已经介绍过非父子组件通信的几种方式中,其中一种就是通过Context来实现非父子组件通信。这里我们在高阶组件中继续使用Context来实现非父子组件通信。也就是说加强版的非父子组件通信。下面我们来看一下具体实现。
示例代码
import React,{PureComponent} from "react";
import ThemeContext from "./context/theme_context";
import Product from "./pages/Product";
export class App extends PureComponent{
render(){
return (
<div>
<ThemeContext.Provider value={{color:"red",size:30}}>
<Product></Product>
</ThemeContext.Provider>
</div>
)
}
}
export default App
上面代码中,我们通过ThemeContext.Provider组件将color和size属性传递给了Product组件。
我们先来看Product组件的代码:
Product组件代码
import React,{PureComponent} from "react";
import ThemeContext from '../context/theme_context'
import withTheme from "../hoc/with_theme"
// export class Product extends PureComponent{
// render(){
// return (
// <div>
// Product:
// <ThemeContext.Consumer>
// {
// value => {
// return <h2>theme:{value.color}-{value.size}</h2>
// }
// }
// </ThemeContext.Consumer>
// </div>
// )
// }
// }
// export default Product
export class Product extends PureComponent {
render(){
const { color,size } = this.props
return (
<div>
<h2>Product:{color}-{size}</h2>
</div>
)
}
}
export default withTheme(Product)
看到上面注释的代码,我们发现Product组件中并没有使用ThemeContext.Consumer组件,而是使用了withTheme高阶组件。我们来看一下withTheme高阶组件的代码:
with_theme.jsx代码
import ThemeContext from "../context/theme_context";
function withTheme(OriginComponent){
return (props) => {
return (
<ThemeContext.Consumer>
{
value => {
return <OriginComponent {...value} {...props}></OriginComponent>
}
}
</ThemeContext.Consumer>
)
}
}
export default withTheme
上面代码中,withTheme高阶组件接收一个组件作为参数,然后返回一个新的组件。这个新的组件中,使用了ThemeContext.Consumer组件,并且使用了value属性,这个属性就是通过ThemeContext.Provider组件传递给的属性。
上面两个代码片段中都使用了theme_context.jsx
文件,我们来看一下这个文件的代码:
theme_context.jsx代码
import { createContext } from "react";
const ThemeContext = createContext()
export default ThemeContext
通过上面的代码,我们实现了非父子组件通信。就直接通过创建一个Context对象,然后通过Provider组件将color和size属性传递给Product组件。
在react中,我们最常用的就是hocks
,也就是高阶组件。通过高阶组件我们可以封装一些常用的功能,然后在项目中直接使用这些高阶组件即可。
最后我们来看一下浏览器中运行效果:
感谢观看,我们下次见!
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我