React createClass 和 React.Component 有什么区别?

以前是这样写的

let app = React.createClass({
    getInitialState: function(){
        // some thing
    }
})

然后也看到用 React.Component,于是


class TodoApp extends React.Component{
    getInitialState(){
         // some thing
    }
}

但是压根没有执行 getInitialState,控制台提示

Warning: getInitialState was defined on TodoApp, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?

其实吧,

React在ES6的实现中去掉了getInitialState这个hook函数,规定state在constructor中实现
官网上有提及两者:

The API (via 'extends React.Component') is similar to React.createClass with the exception of getInitialState. Instead of providing a separate getInitialState method, you set up your own state property in the constructor.

也就是说 通过es6类的继承实现时 state的初始化要在constructor中声明

class exampleComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {example: 'example'}
    }
}
posted @   Sameen  阅读(245)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示