今天小编给大家分享一下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 {
//声明接收context
static contextType = MyContext
render() {
const {username,age} = this.context
return (
<div className="grand">
<h4>我是C组件</h4>
<h5>我从A组件接收到的用户名:{username},年龄是{age}</h5>
</div>
)
}
}
// function C() {
// return (
// <div className="grand">
// <h4>我是C组件</h4>
// <h5>
// 我从A组件接收到的用户名:
// {/* <Consumer>{(value) => `${value.username},年龄是${value.age}`}</Consumer> */}
// </h5>
// </div>
// );
// }
以上就是“React Context如何使用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.csdn.net/qq_45030898/article/details/129315791