Use scenarios
(Top Component) -》Component B (Sub Component) -》Component C (Sunzi Component)
(Top Component) -》Component B (Sub Component), Component C (Sunzi Component)...Many components (each component needs to be transferred to props)
There are many ways to pass data to component C.
1. Pass to C component layer by layer through props
2. Through global objects
Using Provider can solve the problem of data transmission layer by layer and each component has to pass props;
Three nested components: A B C
Scenario: If component C wants to obtain the properties of component A, it is generally practiced to pass it down layer by layer through A–B–C.
Disadvantages: Trouble using, easy to make mistakes, errors in the middle, and subsequent errors
class A extends { state = { name: 'A' } render(){ return ( <div> <B name={}> </div>) } }
// Component Bclass Father extends { render(){ return ( <div> <C age={}> </div>) } }
// Component Cclass C extends { render(){ return ( <div> {} </div> } }
Simple implementation of a Provider ==》Simplifies property delivery
Using react's context to implement a provider, any descendant component can directly obtain the properties of the top-level component through context.
// Component Aimport Provider from './provider' import B from './B'; <Provider info={{name:'max', age: 13}}> <B/> </Provider>
// Simple Provider componentimport React, { Component,Children } from 'react'; import PropTypes from "prop-types" import A from './A' export default class Provider extends { static childContextTypes = { store: }; constructor(props){ super(props) = {...props} } getChildContext(){ return {store:} } render(){ return ( <div> {} </div>) } }
// Component Cimport React, { Component } from 'react'; import PropTypes from "prop-types" export default class C extends { // It must be stated that react believes that global variables are not good static contextTypes = { store: }; render(){ return ( <div> <h1>{}</h1> // Here we directly obtain the attribute value provided by the provider </div>) } }
This is the end of this article about the detailed explanation of the Provider component in React. For more related React Provider component content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!