https://dmitripavlutin.com/react-context-and-usecontext/
context是什么
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
define our global data in one place and access from anywhere in our app
应用场景
You can hold inside the context:
-global state
-theme
-application configuration
-authenticated user name
-user settings
-preferred language
-a collection of services
The Context API in React provides you with built-in functions and components to avoid prop-drilling in your component tree. The React Hook useContext() applies the same functionality in a streamlined, functional component body in one call.
1.React.createContext
2.Context.Provider
3.Context.Consumer
React offers the createContext() method to assist in passing data as a prop.
const colors = {
blue: "#03619c",
yellow: "#8c8f03",
red: "#9c0312"
};
export const ColorContext = React.createContext(colors.blue);
This will allow the .createContext() method to subscribe the property colors.blue as a prop from one component to another.
The context object contains a Provider function which we wrap our rendered child component in.
import React from 'react';
import { ColorContext } from "./ColorContext";
function App() {
return (
<ColorContext.Provider value={colors}>
<Home />
</ColorContext.Provider>
);
}
Here, the Home component will absorb the data within your ColorContext function. Child components of Home will also obtain the data from ColorContext.
You can also apply the .Consumer component to subscribe to a context’s changes. This is available in both class and functional components.
return (
<ColorContext.Consumer>
{colors => <div style={colors.blue}>Hello World</div>}
</ColorContext.Consumer>
);
Whenever the context changes, the .Consumer component will update and adjust your application based on the modification.
The useContext() method accepts a context within a functional component, and works with a .Provider and .Consumer component in one call.
import React, { useContext } from "react";
import ColorContext from './ColorContext';
const MyComponent = () => {
const colors = useContext(ColorContext);
return <div style={{ backgroundColor: colors.blue }}>Hello World</div>;
};
When a change triggers, the useContext() method will subscribe update with the latest context value. Compared to the Context API, the useContext() method allows you to share and pass data throughout your application in fewer lines of code.
useContext
网友评论