一、类组件和函数组件
函数组件:(把它看作一种样式组件,展示样式)
函数组件只能实现非常简单的渲染功能。只是进行页面的展示和数据的渲染。没有逻辑的处理。也就是组件的内部是没有自己的数据和状态的。它是无状态组件。
通常仅是接受外部传来的数据进行展示,不涉及state,只根据props,不用this.props
export default function PickerButton(props){
const { key1,children }=props
return(
<div className='picker-button'>
<span>{key1}</span>
<div>{children}</div>
</div>
)
}
【写法】写一个function并导出,return一个结构,通过props获取数据;
调用的时候,将变量值通过属性的方式注入
export default function Headertitle({key1,key2,children}){
const
return (
<div>helloworld {key1}{key2}
<div>{children}</div>. //children为一个html结构(div。。。。)
</div>
)
}
<HeaderTitle
key1='daming',
key2='12',
children={<div>你好</div>}
/>
类组件:
在里面可以写入状态、生命周期、构造函数
写法:继承React.componnent
export default HeaderTitle extends React.component {
constructor(props){
super(props) //constructor和 super同时必须有(不写也可,会默认有)
this.state={
name:'daming',
age:12,
sex:man
}
this.showname= function() { //这种写法绑定在实例对象上
console.log(this.name)
}
}
showAge = () => { //这种写法绑定在实例对象上
console.log('age')
}
showSex(){ //这种写法在原型对象上,class的prototype属性
console.log('sex')
}
render(
const {key1,key2}=this.props //需要数据由此传递
return(
<div>{key1}{key2}</div>
)
)
}
<HeaderTitle
key1='daming'
key2='12'
/>
super调用父类的构造器;
super必须在this之前使用
参考:
ES6中的class的详解