学无先后,达者为师

网站首页 编程语言 正文

React 中的 context使用方法

作者:多乐_π 更新时间: 2023-07-15 编程语言

什么是上下文?

全局变量就是全局的上下文,全局都可以访问到它;上下文就是你运行一段代码,所要知道的所有变量。

三大件

  1. React.createContext(): context 的初始化
  2. provider: 提供context的父组件,用来包裹需要context的子组件的
  3. 子组件获得context的方法
  4. 代码如5:
  5. //1.要先创建createContex
    export const UserContext = React.createContext(defaultValue);
    
    
    //2.Provider 指定使用的范围
    
    render() {
        return (
          <UserContext.Provider value={this.state} >
            {this.props.children}
          </UserContext.Provider>
        );
      }
    
    
    
    
    
    
    //最后在子组建使用
    
    import { withContext } from "../../contexts";
    import { UserState, UserContext } from "../../contexts/user";
    
    class TestComponent extends React.Component<UserState, State> {
    
    
    
    }
    
    export default withContext(UserContext)(TestComponent);

原文链接:https://blog.csdn.net/weixin_45481456/article/details/131635479

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新