React,父组件设置的context默认值,如何在父组件使用?

下面这种试过不行!

//index.js

constructor(props, context) {
    super(props, context)
    this.context = {
        modelname: 'apiConfigurationModel',
    }
}

getChildContext() {
    return this.context
}

为了在父级组件使用和子组件同一个context

阅读 1.9k
1 个回答

this.context是用来读取这个component的父级components传下来的context值啊,你这样写会出bug的。。。
加默认值嘛,何必执着于一定要放在context里。。。
比如可以:

const modelname = 'apiConfigurationModel';
class comp extends React.Component {
  getChildContext() {
    return {
      modelname
    };
  }
}

再如:

class comp extends React.Component {
  static modelname = 'apiConfigurationModel';
  getChildContext() {
    return {
      modelname: comp.modelname
    };
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题