Context
Introduction and Foreword
Context provides a way to share this class between components without explicitly passing props layer by layer through the component tree.
Simple understanding
When we want to pass the outermost attribute to the innermost component, we don’t need to pass layer by layer to child component.
Simple logic
The outermost component creates a Context object.
The outermost component passes data in a Provider package.
The value is evaluated by Consumer if necessary.
The API is explained under the code demo.
Minimal code demo
./theme.ts
import { createContext } from 'react';
export const ThemeContext = createContext({} as any); // Here you can define default values in '{}'
Copy the code
index.tsx
(page)
import React, { useState } from 'react';
import { ThemeContext } from './theme';
import BigComp from './BigComp'; // The outer component, the code below
export default() = > {const [themeValue, setThemeValue] = useState('light');
return (
<ThemeContext.Provider// Set the parameters to be passed downvalue={{
theme: themeValue.changeTheme:() = >{ setThemeValue('dark'); }}} >,<BigComp />
</ThemeContext.Provider>
);
};
Copy the code
BigComp.tsx
// Outer component
import React from 'react';
import SmallComp from './SmallComp'; // Inner component, see code below
export default() = > (<div>
this is a BigComp
<SmallComp />
</div>
);
Copy the code
SmallComp.tsx
// Inner component
import React from 'react';
import { ThemeContext } from './theme';
export default() = > {return (
<ThemeContext.Consumer>
{({ theme, changeTheme }) => (
<div
onClick={()= > {
changeTheme();
}}
>
this is small components. theme:{theme}
</div>
)}
</ThemeContext.Consumer>
);
};
Copy the code
API (seeOfficial document)
The documentation on the official website has been written very clearly. Here are some examples of the documentation.
createContext
Create a Context object. When we need to fetch the value of the context, the current context value is read from the Provider closest to the component tree.
The defaultValue parameter takes effect only if the component does not match the Provider in the tree.
Provider
Context objects all return to the Provider component. A Provider can contain multiple consumer components (subcomponents).
The Provider receives a value attribute.
. For example: “ThemeContext Provider value = {} ‘light’ > < / ThemeContext Provider >
When a Provider’s value changes, all of its internal consuming components are rerendered.
Multiple providers can also be nested, with the inner layer overwriting the data in the outer layer.
Ex. :
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={signedInUser}>
<Layout />
</UserContext.Provider>
</ThemeContext.Provider>
Copy the code
Consumer
Receives the current context value and returns a React node.
Example: < themecontext.consumer >{value =>
}
Writing is not easy, give a star then go ~