• react contextType,useContext,Provider参数简易传递


    //useCallback
    import React, { Fragment, PureComponent, memo, useContext, createContext } from 'react';
    // import About from './About';
    const CountContext = createContext();  //创建context
    
    //类方式
    class Foo extends PureComponent {
      static contextType = CountContext;   //注入this.context,static 表示静态方法
      render() {
        let count = this.context;
        return (
          <div>{count}</div>
        )
      }
    }
    //hooks方式
    const Fbr = memo(() => {
      const count = useContext(CountContext);   //CountContext是上文创建context对象
      return (
        <div>
          {count}
        </div>
      )
    });
    
    class App extends PureComponent {
      state = {
        count: 0,
        name: 0
      }
      render() {
        return (
          <Fragment>
            <CountContext.Provider value={this.state.count}>
              <Foo count={this.state.count} ></Foo>
              <Fbr></Fbr>
            </CountContext.Provider>    //Provider传递参数
            <button onClick={() => { this.setState(() => ({ count: this.state.count + 1 })) }}>加count</button>
          </Fragment>
        )
      }
    }
    export default App;
    

      

  • 相关阅读:
    Dynamics CRM9.0更新了Chrome后菜单按钮变形
    质量属性
    机器学习理解
    大道之简的理解
    架构之美理解
    1.13
    1.12
    1.11
    1.10
    Flex 替换输入的字符串
  • 原文地址:https://www.cnblogs.com/uimeigui/p/12655576.html
Copyright © 2020-2023  润新知