React 自定义组件的两种方式

React 自定义组件的两种方式:

函数组件和类组件

 

第一种,函数组件(无状态,即无私有属性,state):

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

第二种,类(ES6)组件(有状态。即有私有属性,state):

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

一般完整的类组件,示例:

import React, { Component } from "react"; 

class Hello extends Component {

// 构造函数
constructor(props){
super(props);

// 声明私有数据 (类似vue中data的作用)
this.state = { msg:'123' }
}
render() {
console.log(this.state)
// 打印查看
return (
<div>
{/* 在组件中使用私有数据 */}
<h1>{this.state.msg}</h1>
</div> );
}
}
export default Hello;

什么情况下使用有状态组件?什么情况下使用无状态组件?

如果组件内,不需要有私有的数据,即不需要  state,此时,使用函数创建无状态组件比较合适;
如果组件内,需要有自己私有的数据,即需要  state,则,使用 class 关键字 创建有状态组件比较合适;

组件中的 props 和 state 之间的区别

props 中存储的数据,都是外界传递到组件中的;
props 中的数据,都是只读的;
state 中的数据,都是组件内私有的;
state 中的数据,都是可读可写的;
props 在 有状态组件 和 无状态组件中,都有;
state 只有在 有状态组件中才能使用;无状态组件中,没有 state;

猜你喜欢

转载自www.cnblogs.com/zqblog1314/p/12905423.html