今天小编给大家分享一下React Context如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。1.Cont
今天小编给大家分享一下React Context如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
一种React组件间通信方式, 常用于【祖组件】与【后代组件】间通信
import React, { Component } from "react";import "./index.CSS";export default class A extends Component { state = { username: "tom", age: 18 }; render() { const { username, age } = this.state; return ( <div className="parent"> <h4>我是A组件</h4> <h5>我的用户名是:{username}</h5> <B username={username} age={age}></B> </div> ); }}class B extends Component { render() { console.log(this.props); const { username, age } = this.props; return ( <div className="child"> <h4>我是B组件</h4> <C username={username} age={age} /> </div> ); }}function C(props) {const { username, age } = props; return ( <div className="grand"> <h4>我是C组件</h4> <h5> 我从A组件接收到的用户名:{username},年龄是{age} </h5> </div> );}
这里C组件用了下函数式组件的写法
但是这种写法有很多的不太好的地方,如果层级再深一点呢,传的值再多一点呢。肯定会有很多的重复代码出现,而且我只想要祖组件和孙组件通信,这样写的话其实是每个组件都在通信了的。
Context的就可以挺好的适用于这种场景
创建Context容器对象:
const XxxContext = React.createContext()
2) 渲染子组时,外面包裹xxxContext.Provider, 通过value属性给后代组件传递数据:
<xxxContext.Provider value={数据}>
子组件
</xxxContext.Provider>
3) 后代组件读取数据:
//第一种方式:仅适用于类组件
static contextType = xxxContext // 声明接收context
this.context // 读取context中的value数据
//第二种方式: 函数组件与类组件都可以
<xxxContext.Consumer>
{
value => ( // value就是context中的value数据
要显示的内容
)
}
</xxxContext.Consumer>
上代码
import React, { Component } from "react";import "./index.css";//创建Context对象const MyContext = React.createContext();const { Provider, Consumer } = MyContext;export default class A extends Component { state = { username: "tom", age: 18 }; render() { const { username, age } = this.state; return ( <div className="parent"> <h4>我是A组件</h4> <h5>我的用户名是:{username}</h5> //如果传的只有一个值例如username,应该式value={username},后面就是直接获取了,不需要再属性名取值了 <Provider value={{ username, age }}> <B /> </Provider> </div> ); }}class B extends Component { render() { return ( <div className="child"> <h4>我是B组件</h4> <C/> </div> ); }} class C extends Component {//声明接收contextstatic contextType = MyContextrender() {const {username,age} = this.contextreturn (<div className="grand"><h4>我是C组件</h4><h5>我从A组件接收到的用户名:{username},年龄是{age}</h5></div>)}} // function C() {// return (// <div className="grand">// <h4>我是C组件</h4>// <h5>// 我从A组件接收到的用户名:// {}// </h5>// </div>// );// }
以上就是“React Context如何使用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注编程网精选频道。
--结束END--
本文标题: React Context如何使用
本文链接: https://www.lsjlt.com/news/350822.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0