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'}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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