新建context.js
// context.js
import { createContext } from "react";
export default createContext();
Provider和Consumer
// App.jsx
import MyContext from './code/components/context'
import Child from './Child'
// const ThemeContext = React.createContext('light');
function App() {
return (
<MyContext.Provider value='哈哈哈'>
<div className="App">
<Child></Child>
</div>
</MyContext.Provider>
);
}
export default App;
// Child.jsx
import React, { Component } from 'react'
import MyContext from './context'
export default class Child extends Component {
render() {
return (
<MyContext.Consumer>
<div>
{
(value)=> {
return <div>{value}</div>
}
}
</div>
</MyContext.Consumer>
)
}
}
函数组件使用Provider和useContext
// Child.jsx
import React,{useContext} from 'react'
import MyContext from "./context";
export default function Child() {
const context = useContext(MyContext);
return (
<div>
<div>{context}</div>
</div>
)
}
类组件使用Provider和class的contextType属性
// Child.jsx
import React, { Component } from 'react'
import MyContext from './context'
export default class Child extends Component {
static contextType = context
render() {
return (
<div>{this.context}</div>
)
}
}
参考文档React官网