React中Provider組件詳解(使用場景)
使用場景
1.A(頂級組件)-》B組件(子組件)-》C組件(孫子組件)
2.A(頂級組件)-》B組件(子組件)、C組件(孫子組件)…很多組件(每個組件都需要傳props)
A組件傳遞數(shù)據(jù)給C組件實(shí)現(xiàn)方式有很多種
1.通過props層層傳遞到C組件
2.通過全局對象
使用Provider可以解決數(shù)據(jù)層層傳遞和每個組件都要傳props的問題;
三個嵌套組件:A B C
場景:組件 C 想要取組件A 的屬性,一般做法通過A–B–C一層一層傳遞下來
缺點(diǎn):使用麻煩,容易出錯,中途出錯,后續(xù)都錯
class A extends React.Component { state = { name: 'A' } render(){ return ( <div> <B name={this.name.name}> </div>) } }
// B組件 class Father extends React.Component { render(){ return ( <div> <C age={this.props.name}> </div>) } }
// C組件 class C extends React.Component { render(){ return ( <div> {this.props.name} </div> } }
簡單實(shí)現(xiàn)一個Provider ==》簡化屬性傳遞
利用react的context實(shí)現(xiàn)一個provider,任意后代組件可以直接通過context取到頂級組件的屬性
// A組件 import Provider from './provider' import B from './B'; <Provider info={{name:'max', age: 13}}> <B/> </Provider>
// 簡單的Provider組件 import React, { Component,Children } from 'react'; import PropTypes from "prop-types" import A from './A' export default class Provider extends React.Component { static childContextTypes = { store: PropTypes.object.isRequired }; constructor(props){ super(props) this.store = {...props} } getChildContext(){ return {store:this.store} } render(){ return ( <div> {this.props.children} </div>) } }
// C組件 import React, { Component } from 'react'; import PropTypes from "prop-types" export default class C extends React.Component { // 必須要申明,react認(rèn)為全局變量不好 static contextTypes = { store:PropTypes.object.isRequired }; render(){ return ( <div> <h1>{this.context.store.info.age}</h1> // 這里直接獲取provider提供的屬性值 </div>) } }
到此這篇關(guān)于React中Provider組件詳解的文章就介紹到這了,更多相關(guān)React Provider組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
簡析React Native startReactApplication 方法
這篇文章主要介紹了React Native startReactApplication 方法簡析,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09手把手教你從零開始react+antd搭建項(xiàng)目
本文將從最基礎(chǔ)的項(xiàng)目搭建開始講起,做一個基于react和antd的后臺管理系統(tǒng),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06react拖拽react-beautiful-dnd一維數(shù)組二維數(shù)組拖拽功能
二維數(shù)組可以拖拽,但是不可以編輯+拖拽,如果想要實(shí)現(xiàn)編輯+拖拽,還是需要轉(zhuǎn)換成一維數(shù)組,本文給大家介紹react拖拽react-beautiful-dnd的相關(guān)知識,感興趣的朋友跟隨小編一起看看吧2024-03-03react中實(shí)現(xiàn)修改input的defaultValue
這篇文章主要介紹了react中實(shí)現(xiàn)修改input的defaultValue方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05