Context API:
React.createContext(
defaultValue):
创建一个context对象。当React渲染订阅了这个Context对象的组件,这个组件会从组件树中离自身组件最近的那个匹配的Provider中读取到当前的context值。Context.Provider:接收一个value属性,传递给消费组件,允许消费组件订阅context变化。
class.contextType :挂载在class上的contextType属性会被重赋值给一个由React。createContext()创建的Context对象。则使用this.context来消费最近Context上的那个值。
useContext:接收一个context对象并返回该context的当前值。当前的context值由上层组件中距离当前组件最近的Provider的value prop觉得,只用在function
Context.Consumer:这种方法需要一个函数作为子元素。这个函数接收当前的 context 值,并返回一个 React 节点。传递给函数的 value
值等价于组件树上方离这个 context 最近的 Provider 提供的 value
值。
createContext:
import React from "react"; export const ThemeContext = React.createContext(); export const ThemeProvider = ThemeContext.Provider;
export const ThemeConsumer = ThemeContext.Consumer;
Provider:
import React, { Component } from "react"; import { ThemeProvider } from "../Context"; import HomePage from "./HomePage"; import UserPage from "./Userpage"; class ContextPage extends Component { constructor(props) { super(props); this.state = { theme: { themeColor: "red", }, }; } render() { const { theme } = this.state; return ( <div> <h1>ContextPage</h1> <ThemeProvider value={theme}> <HomePage /> <UserPage /> </ThemeProvider> </div> ); } } export default ContextPage;
class.contextType:
import React, { Component } from "react"; import { ThemeContext } from "../Context"; class APage extends Component { // 方法1 // static contextType = ThemeContext; render() { const { themeColor } = this.context; console.log(this, "this"); return ( <div> <h3 className={themeColor}>APage</h3> </div> ); } } // 方法2 HomePage.contextType = ThemeContext; export default APage;
useContext:
import React, { useContext } from "react"; import { ThemeContext } from "../Context"; export default function BPage(props) { const ctx = useContext(ThemeContext); return ( <div> <h3 className={ctx.themeColor}>BPage</h3> </div> ); }
Consumer:
import React, { Component } from "react"; import { ThemeConsumer } from "../Context"; export default class ConsumerPage extends Component { render() { return ( <div> <h3>ConsumerPage</h3> <ThemeConsumer> {(themeContext) => <div className={themeContext.themeColor}>omg</div>} </ThemeConsumer> </div> ); } }
参考 && 感谢 各路大神:
https://zh-hans.reactjs.org/docs/context.html