React constructor() 方法
constructor() 方法格式如下:
constructor(props)
在 React 组件挂载之前,会调用它的构造函数 constructor()。
React.Component 子类实现构造函数时,应在其他语句之前前调用 super(props)。
以下实例在创建组件时,React 都会调用构造函数:
实例
class
Header
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
favoritewebsite
:
"
yssmx
"
}
;
}
render
(
)
{
return
(
<
h1
>我喜欢的网站
{
this
.
state
.
favoritewebsite
}
</
h1
>
)
;
}
}
ReactDOM
.
render
(
<
Header
/>,
document
.
getElementById
(
'
root
'
)
)
;
尝试一下 »
在 React 中,构造函数仅用于以下两种情况:
- 通过给 this.state 赋值对象来初始化内部 state。
- 为事件处理函数绑定实例。
如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
在 constructor() 函数中不要调用 setState() 方法。如果你的组件需要使用内部 state,请直接在构造函数中为 this.state 赋值初始 state:
constructor(props) { super(props); // 不要在这里调用 this.setState() this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); }
只能在构造函数中直接为 this.state 赋值。如需在其他方法中赋值,你应使用 this.setState() 替代。