React 中的 定义组件的 两种方式

React 中创建 Components 的方式有两种:Function and Class

定义一个组件最简单的方法就是写一个 JavaScript 函数

function Welcome(props) { return <h1>Hello, {props.name}</h1> }

因为Welcome函数接受单个携带数据的props对象并且返回一个React元素,所以它就是一个组件。这种通过字面表达式函数创建的组建通常叫做functional

当然你也可以通过ES6 class的语法来定义一个组件

class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }

要说明的是从 React's 的角度以上两种定义组件的效果是相等的

那什么时候需要用 Class 方式来定义组件呢

在需要使用一些额外的特点的时候比如 state 和 lificycle 的情况下,就应该使用 Class 来定义组件

  • 在 Class 中添加 State

class Clock extends React.Component {
constructor(props) { // 注意这里将props传入了构造器 Class 方式创建的组件必须总是调用带有 props 的构造器
super(props);
this.state = {date: new Date()};
}

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

  

  • 在 Class 中添加 lifecycle方法

  在有很多组件的大型应用中,当在组件被销毁的时候及时地释放资源是非常重要的。

class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}

// 当 Clock 第一次渲染到 DOM 时创建一个定时器,在 React 中叫做 mounting
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

// 当 Clock 被移除的时候需要清理掉这个定时器, 在 React 中叫做 unmounting
componentWillUnmount() {
clearInterval(this.timerID);
}

tick() {
this.setState({
date: new Date()
});
}

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

ReactDOM.render(
<Clock />,
document.getElementById('root')
);

  componentDidMount 和 componentWillUnmount 被叫做 lifecycle hooks

  原文:https://blog.csdn.net/gx15366039985/article/details/78142778

猜你喜欢

转载自www.cnblogs.com/showcase/p/10577055.html