ES6中的childContextTypes

Chr*_* G. 16 javascript ecmascript-6 reactjs es2015

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

var A = React.createClass({

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

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

    render: function() {
         return <B />;
    }
});
Run Code Online (Sandbox Code Playgroud)

cut*_*ine 22

既然你正在使用Babel,你可以static在代码中使用(ES7),如下所示:

export default class A extends React.Component {

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

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

  render() {
    return <B />
  }
}
Run Code Online (Sandbox Code Playgroud)

更多信息:对ES6 +做出反应


eva*_*kes 14

问题是childContextTypes需要在"类"上定义,这就是做什么的static.所以这两个解决方案似乎有效:

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

    this.constructor.childContextTypes = {
      name: React.PropTypes.string.isRequired
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

要么

class A extends React.Component {

}

A.childContextTypes = {
  name: React.PropTypes.string.isRequired
};
Run Code Online (Sandbox Code Playgroud)


Chr*_* G. 0

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

班级 { 。,, };

childContextTypes() {..}

或者等ES7有静态属性。