我正在 React 中尝试 ES6 语法,并编写如下组件:
export default class Loginform extends React.Component {
getInitialState() {
return {
name: '',
password: ''
};
};
}
但是浏览器让我担心:
Warning: getInitialState was defined on Loginform, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
我可以使用传统语法 var Loginform = React.createClass
来处理它,但是正确的 ES6 语法是什么?
另一件小事,我认为在传统语法中 React.createClass
是一个对象,因此其中的函数用逗号分隔,但是使用它需要的 extends
类分号,我不太明白。
最佳答案
ES6 类方法声明之间不需要分号或逗号。
对于 ES6 类,getInitialState
已被弃用,转而在构造函数中声明初始状态对象:
export default class Loginform extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
name: '',
password: ''
};
};
}
关于reactjs - 类扩展了 React.Component 不能在 React 中使用 getInitialState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447149/