先说一说context是干什么的:
跨层级通信
一般组件通信的方法都是通过props来传递,不过这种方法当有了第三级或往后孙孙组件的时候就显得比较繁琐。以及不好修改。这时我们可以使用context来管理这些数据,不管多少层级都能让想要使用这些数据的组件能拿到。还有别的方法,mobx或redux。这些可以自行了解
说一下文件目录以及思路:
创建index文件作为父组件,child1组件为子组件,child2为子子组件。同级下创建一个store.js中存放数据和创建context。
index中呢引入child1组件,child1组件呢引入child2组件。我们现在要做的就是不使用props在child2中获取index父级的数据。
store.js :
可以分为三步:1.引入React。2.创建数据。3.创建导出context
import React from 'react';
这里我们可以定义数据格式
export const Resume = {
base: {
name: '',
age: ''
},
exp: {
year: '',
job: ''
},
lists: [],
}
通过createContext创建context并导出
export const ResumeContext = React.createContext(Resume);
index.jsx作为父组件,也可以总结为三个步骤:1.导入。2.注入。3.value赋值
import React, { Component } from 'react';
import Child1 from './child1'
//这里引入的组件大家可以随意定义
import Wei from './weike'
//在这里引入store.js
import { ResumeContext } from './store.js'
class View extends Component {
constructor(props) {
super(props)
this.state = {
// 一般我们不会在store中写数据,数据在父组件中定义
resume: {
base: {
name: '小红',
age: 1212
}
}
}
}
// 这个方法呢我们可以返回一个组件。
com() {
return <Wei />
}
//也可以返回标签文本
fn() {
return (
<div>这是fn</div>
)
}
// 这个函数接收子组件传过来的参数
parentFn(text) {
console.log(text)
}
render() {
const { resume } = this.state
return (
<div>
<h3>index组件</h3>
// 父组件在传递数据时要用Context.Provider。value中我们可以传多种数据结构
<ResumeContext.Provider value={{
base: resume.base, //基础数据
com: this.com, //组件 调一个方法返回一个组件
com1: <Wei />, //组件 也可以直接调一个组件,
fn: this.fn, // 也可以是文本
callback: this.parentFn //子组件传过来的值,打印出来
}}>
<Child1 />
</ResumeContext.Provider>
</div>
);
}
}
export default View;
child2作为使用数据的,里面步骤也可以总结为三步:1.引入。2.接收。3.使用。
import React, { Component, useCallback } from 'react';
//引入context
import { ResumeContext, } from './store.js'
class View extends Component {
constructor(props) {
super(props)
this.state = {
}
}
// static 定义
static contextType = ResumeContext;
//这里是传给父组件的参数
componentDidMount() {
const { callback } = this.context;
callback('1212')
// === this.parentFn('1212')
}
render() {
console.log(this.context)
//这里打印的context就相当于props,它是一个对象。里面包含父组件传过来的数据
//解构
const { base, com, com1, fn } = this.context
return (
<div>
<h3>child22222组件</h3>
// 基本数据类型使用
姓名:{base.name}
//com和com1都是调用传来的组件,写法不同而已
{com()}
{com1}
//文本
{fn()}
</div>
);
}
}
export default View;
***子子组件还有一种写法,用Context.Consumer接收
<ResumeContext.Consumer>
{
(value) => (
<div>{this.age(value)}{value.base.name}</div>
)
}
</ResumeContext.Consumer>
child1组件就只是引用了child2组件。没有别的用处
下面看下出来的效果图:
至此context的总结使用方法就大概这些,如有错误欢迎指正