React.createClass 与扩展组件 [英] React.createClass vs extends Component

查看:40
本文介绍了React.createClass 与扩展组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var MyClass = React.createClass({...});

class MyClass extends React.Component{...}

推荐答案

这两种方式取决于你是否使用 ES6 语法,它们也会改变你设置初始状态的方式.

These two ways depend on if you are using ES6 syntax or not, and they also change the way you set up your initial state.

当使用 ES6 类时,你应该在 constructor 中初始化 state.

When using ES6 classes, You should initialize state in the constructor.

当使用 React.createClass 时,你必须使用 getInitialState 函数.

When using React.createClass you have to use the getInitialState function.

ES6 类语法:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state, this is ES6 syntax (classes) */ };
  }
}

ES5 React.CreateClass 语法:

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

这两种方法都以相同的方式设置初始状态.

These will both work the same way to set up initial state.

这篇关于React.createClass 与扩展组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆