context.js文件
import React from "react";
export const resume = {
base: {
name: "",
age: "",
genders: "male",
}
};
export const context = React.createContext(resume.base);
index.jsx(最大的父组件)
import React, { Component } from "react";
import Child from "./Children";
import { context, resume } from "./context";
import About from "./about";
class index extends Component {
constructor() {
super();
this.state = {
base: { name: "", age: "", genders: "male" },
};
}
_init() {
this.setState({
base: {
name: "新名字",
age: "32",
genders: "nv",
},
});
}
componentDidMount() {
setTimeout(() => {
this._init();
}, 2000);
}
contextFn(txt) {
console.log(txt);
}
left() {
return <div>left</div>;
}
com() {
return <About />;
}
render() {
console.log(resume);
return (
<>
<context.Provider
value={{
base: this.state.base,
callback: this.contextFn,
left: this.left,
com: this.com,
}}
>
<Child />
</context.Provider>
</>
);
}
}
export default index;
直系子级Children.jsx
import React, { Component } from "react";
import Child2 from "./Children2";
class Children extends Component {
render() {
return (
<div>
<b>大子级</b>
<Child2 />
</div>
);
}
}
export default Children;
非直系子级Children2.jsx
import React, { Component } from "react";
import { context } from "./context";
class Children extends Component {
list(txt) {
console.log(txt);
}
componentDidMount() {
const { genders } = this.context;
}
render() {
const { genders } = this.context;
return (
<>
{genders}++
<context.Consumer>
{(value) => {
return (
<b>
{this.list(value.base)}
{value.base.genders}
{value.left()}
{value.com()}
{value.callback("fn")}
</b>
);
}}
</context.Consumer>
</>
);
}
}
export default Children;
About.jsx组件(就是需要传递的一个组件)