zoukankan      html  css  js  c++  java
  • react中Context的使用

    Context的使用

    Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。

    props单向数据流动:

    https://image-static.segmentfault.com/134/351/1343511491-5c219fdde2a7b_articlex

    如果觉得Props传递数据很繁琐,可以采用context,进行跨组件传递数据
    https://image-static.segmentfault.com/137/153/1371537545-5c21a54e769ca_articlex

    例如给子代元素传递一笔钱(手动添加狗头)

    为了后续使用方便,封装一个组件

    import {createContext} from 'react';
    let moneyContext = createContext()
    export default {
       moneyContext
    }

    App.js

    import React,{Component} from 'react';
    import ContextParent from "./ContextParent"
    import moneyContext from "./moneyContext"
    class App extends Component{
      state = {
        money:100
      }
      render(){
        return (
             //提供者的value属性可以给所有的后代元素提供数据
          <moneyContext.Provider value={{
            money:this.state.money
          }}>
            <ContextParent/>
          </moneyContext.Provider>
        )
      }
    }
    
    export default App;

    ContextParent

    import React, { Component,createContext } from 'react'
    import GrandChild from "./GrandChild"
    import moneyContext from "./moneyContext"
    export default class ContextParent extends Component {
        render() {
            return (
                   //通过公共实例的Context的Consumer,内部子元素写成一个函数,参数就可以获取value值了
                    <moneyContext.Consumer>
                        {
                            (value)=>{
                                return (
                                    <div>
                                        ContextParent组件获取App传递来的money === {value.money}
                                        <GrandChild />
                                    </div>
                                )
                            }
                        }
                    </moneyContext.Consumer>
            )
        }
    }

    GrandChlid

    import React, { Component } from 'react'
    import moneyContext from "./moneyContext"
    export default class GrandChild extends Component {
        render() {
            return (
                <moneyContext.Consumer>
                    {
                        value=>{
                            return (
                                <div>
                                    我是GrandChild组件---{value.money}
                                </div>
                            )
                        }
                    }
                </moneyContext.Consumer>
            )
        }
    }
    请用今天的努力,让明天没有遗憾。
  • 相关阅读:
    数组模拟队列实现
    Vue之模板语法
    初识Vue之helloworld
    二、Lambda表达式
    一、函数式编程
    SpringCloudAlibaba之Nacos
    SpringCloudAlibaba之Sentinel
    spring的随笔2
    spring的小想法1
    关于hibernate的一些看法
  • 原文地址:https://www.cnblogs.com/cupid10/p/15617664.html
Copyright © 2011-2022 走看看