javascript ES6 中的 childContextType

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32078493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:49:07  来源:igfitidea点击:

childContextTypes in ES6

javascriptreactjsecmascript-6es2015

提问by Chris G.

How would you write the object childContextTypes in ES6?

你会如何在 ES6 中编写对象 childContextTypes?

var A = React.createClass({

    childContextTypes: {
         name: React.PropTypes.string.isRequired
    },

    getChildContext: function() {
         return { name: "Jonas" };
    },

    render: function() {
         return <B />;
    }
});

回答by cutemachine

Since you are using Babel anyway, you can use static(ES7) in your code like this:

由于您无论如何都在使用 Babel,因此您可以static在代码中使用(ES7),如下所示:

export default class A extends React.Component {

  static childContextTypes = {
    name: React.PropTypes.string,
  }

  getChildContext() {
    return { name: "Jonas" }
  }

  render() {
    return <B />
  }
}

More info: React on ES6+

更多信息:在 ES6+ 上反应

回答by evanbikes

The issue is that childContextTypesneeds to be defined on the "class", which is what staticdoes. So these two solutions seem to work:

问题是childContextTypes需要在“类”上定义,这是什么static。所以这两个解决方案似乎有效:

class A extends React.Component {
  constructor() {
    super(...arguments);

    this.constructor.childContextTypes = {
      name: React.PropTypes.string.isRequired
    };
  }
}

Or

或者

class A extends React.Component {

}

A.childContextTypes = {
  name: React.PropTypes.string.isRequired
};

回答by Inessa Pokromkina

try this:

试试这个:

import React, { PropTypes } from 'react';

export default class Grandparent extends React.Component {
  static childContextTypes = {
    getUser: PropTypes.func
  };

   getChildContext() {
    return {
      getUser: () => ({ name: 'Bob' })
    };
  }

  render() {
    return <Parent />;
  }
}

class Parent extends React.Component  {
  render() {
    return <Child />;
  }
}

class Child extends React.Component {
  static contextTypes = {
    getUser: PropTypes.func.isRequired
  };

  render() {
    const user = this.context.getUser();
    return <p>Hello {user.name}!</p>;
  }
}

Source code form here: React ES6 Context

源代码形式在这里: React ES6 Context

回答by Chris G.

The solution was to move "childContextTypes" out of the class:

解决方案是将“childContextTypes”移出类:

class { .,, };

childContextTypes() {..}

班级 { 。,, };

childContextTypes() {..}

Or wait for ES7 to have static properties.

或者等 ES7 有静态属性。

回答by Nick Perkins

If you are using Coffeescript...

如果您使用的是 Coffeescript...

change

改变

childContextTypes:

to

@childContextTypes: