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

    import React, { Component } from 'react'
    const { Provider, Consumer } = React.createContext()
    let data = {
      name: 'lisi',
      age: 18
    }
    
    class B extends Component {
      render() {
        return (
          <Consumer>
            {
              data => {
                return (
                  <div>
                    姓名: {data.name}
                    年龄: {data.age}
                  </div>
                )
              }
            }
          </Consumer>
        )
      }
    }
    class A extends Component {
      render() {
        return (
          <div>
            <B></B>
          </div>
        )
      }
    }
    export default class App extends Component {
      render() {
        return (
          <Provider value={data}>
            <div>
              <A></A>
            </div>
          </Provider>
        )
      }
    }

    现版本采用useContext.

    import React, { useContext } from 'react'
    
    let data = {
        name: 'lisi',
        age: 18
    }
    const context = React.createContext(data)
    
    
    function Dialog(props) {
        return (
            <div>
                {props.ctx.name}
            </div>
        )
    }
    
    export default function App() {
        const ctx = useContext(context)
        return (
            <div>
                <Dialog ctx={ctx}></Dialog>
            </div>
        )
    }
  • 相关阅读:
    es6之class继承
    es6-class基本语法
    vue-cli3搭建pwa项目(一)
    vue 组件的通信方式
    react之组件&props
    React之元素渲染
    JSX
    JSX
    在项目中怎么使用react
    认识react
  • 原文地址:https://www.cnblogs.com/crazy-rock/p/15243755.html
Copyright © 2011-2022 走看看