组件
组件的定义
Class组件
class Clock extends React.Component {
constructor(props) {
super(props); // 必须明确编写
this.state = {date: new Date()}; // 配置state
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
- super(props) 是必须要写的
函数组件
如果你想写的组件只包含一个 render
方法,并且不包含 state,那么使用函数组件就会更简单。我们不需要定义一个继承于 React.Component
的类,我们可以定义一个函数,这个函数接收 props
作为参数,然后返回需要渲染的元素。函数组件写起来并不像 class 组件那么繁琐,很多组件都可以使用函数组件来写。
function Square(props) {
return (
<button className="square" onClick={ props.onClick }>
{props.value}
</button>
);
}
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<Avatar user={props.author} />
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
const user = {}