在Reactor中提供了Context来替代ThreadLocal,可以实现一个跨线程的共享变量的透明方式。本文主要为大家介绍了Context的用法的用法,感兴趣的可以了解一下
1.Context是干嘛的
一种React组件间通信方式, 常用于【祖组件】与【后代组件】间通信
2.可以倒是可以实现的做法-props逐级传递
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 (); } } class B extends Component { render() { console.log(this.props); const { username, age } = this.props; return (我是A组件
我的用户名是:{username}
); } } function C(props) { const { username, age } = props; return (我是B组件
); }我是C组件
我从A组件接收到的用户名:{username},年龄是{age}
这里C组件用了下函数式组件的写法
但是这种写法有很多的不太好的地方,如果层级再深一点呢,传的值再多一点呢。肯定会有很多的重复代码出现,而且我只想要祖组件和孙组件通信,这样写的话其实是每个组件都在通信了的
3.Context
Context的就可以挺好的适用于这种场景
创建Context容器对象:
const XxxContext = React.createContext()
2) 渲染子组时,外面包裹xxxContext.Provider, 通过value属性给后代组件传递数据:
子组件
3) 后代组件读取数据:
//第一种方式:仅适用于类组件
static contextType = xxxContext // 声明接收context
this.context // 读取context中的value数据
//第二种方式: 函数组件与类组件都可以
{
value => ( // value就是context中的value数据
要显示的内容
)
}
上代码
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 (); } } class B extends Component { render() { return (我是A组件
我的用户名是:{username}
//如果传的只有一个值例如username,应该式value={username},后面就是直接获取了,不需要再属性名取值了 ); } } class C extends Component { //声明接收context static contextType = MyContext render() { const {username,age} = this.context return (我是B组件
) } } // function C() { // return ( //我是C组件
我从A组件接收到的用户名:{username},年龄是{age}
//// ); // }我是C组件
//// 我从A组件接收到的用户名: // {/*
//{(value) => `${value.username},年龄是${value.age}`} */} //
到此这篇关于React Context详解使用过程的文章就介绍到这了,更多相关React Context内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!
以上就是React Context详解使用过程的详细内容,更多请关注0133技术站其它相关文章!