class关键字创建组件
index.js文件
import React from 'react'
import ReactDOM from 'react-dom'
// import '@/1-class实例方法和静态方法'
class Hello extends React.Component{
constructor(){
super()
this.state = {
msg:'大家好,Movie'
}
}
//render() 渲染当前组件所对应的DOM元素
render(){
//this.props上的数据是只读的,不可写
//this.state上的数据是可读可写的
// this.state.msg = "awda"
// 在class关键字创建的组件中,可以直接使用外界传递的props参数(直接通过 this.props.** 访问)
return <div>
{/* this表示当前组件的实例对象 */}
组件 -- {this.props.name} -- {this.props.age} -- {this.props.gender}
<hr/>
{this.state.msg}
</div>
}
}
const user = {
name:'ad',
age:11,
gender:'nan'
}
// import '@/2-class继承'
ReactDOM.render(<div>
123
{/* 这里的Hello标签其实是Helle类的一个实例对象 */}
{/* <Hello name={user.name} age={user.age} gender={user.gender}></Hello> */}
<Hello {...user}></Hello>
</div>,document.getElementById('app'))
class关键字创建组件与function创建组件的区别
使用class关键字创建的组件:
有自己的私有数据和生命周期函数
被称为有状态组件
使用function创建的组件:
只有props,没有自己的私有数据和生命周期函数
被称为无状态组件
运行效率高一些
本质区别:有望state属性和生命周期函数
组件中的props和state的区别
props中的数据都是外界传递过来的
state中的数据都是组件私有的(通过Ajax获取的数据,一般都是私有的)
props中的数据都是只读的,不能赋值
state中的数据,都是可读可写的