组件的写法
在react引入hook之前,react的有状态组件的写法都是class写法,在react引入hook之后,react的函数组件也可以使用state了,所以react的有状态组件有两种写法,包括传统的class组件和带有hook函数的组件。这两种组件在项目中是可以互相引用的。不过除非改造项目,一般不建议这么写。注意:我们import
引入函数组件时,组件名称的首字母一定要大写。
传统的class组件写法
下面是一个简单的只带有state的react组件的class写法
//示例来自react官网
// 整个章节中都将使用该 class 的代码片段做示例。
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
state 初始值为 { count: 0 }
,当用户点击按钮后,我们通过调用 this.setSt