一、傻瓜组件和聪明组件
傻瓜组件也叫展示组件,负责根据props展示页面信息。
聪明组件也叫容器组件,负责数据的获取和处理。
二、函数式组件
- 函数式组件是⼀种⽆状态组件,是为了创建纯展示组件,这种组件只负责根据传⼊的props来展示,不涉及到要state状态的操作。
- 组件不会被实例化,整体渲染性能得到提升。
- 组件不能访问this对象。
- 组件⽆法访问⽣命周期的⽅法。
- ⽆状态组件只能访问输⼊的props,同样的props会得到同样的渲染结果,不会有副作⽤。
// 这种写法是新建⼀个组件⻚⾯把组件暴露出去的写法
import React from 'react'
export default function xxx() {
return (
<div>
我是函数式组件
</div>
)
}
// 这种写法是在⻚⾯内部创建组件不⽤给外部使⽤,只供⻚⾯内部使⽤
function xxx() {
return (
<div>
我是函数式组件
</div>
)
}
三、class组件(不常用)
import React, { Component } from 'react'
export default class ConditionLoop extends Component {
render() {
return (
<div>
</div>
)
}
}
四、Purecomponent
PureComponent是内部定制了shouldComponentUpdate⽣命周期的Component,重写了⼀个⽅法来替换shouldComponentUpdate⽣命周期⽅法。
平常开发过程中设计组件能使⽤PureComponent的地⽅都尽量使⽤,使⽤PureComponent可以省去shouldComponentUpdate⽣命周期的代码,代码会简单很多。
两个小原则:
- 确保数据类型是值类型
- 如果是引⽤类型,确保地址不变,同时不应当有深层次数据变化
// 用 Purecomponent 代替生命周期
class Title extends PureComponent {
// shouldComponentUpdate(nextProps){
// return nextProps.title !== this.props.title
// }
render() {
console.log('title组件')
return (
<div>
标题:{this.props.title}
</div>
)
}
}
五、React.memo
React.memo是⼀个⾼阶组件的写法。React.memo让函数组件也拥有了PureComponent的功能。
// 使用React.memo代替以上的title组件,让函数式组件也拥有Purecomponent的功能
const Title = React.memo((props)=>{
console.log('title组件')
return(
<div>
标题:{props.title}
</div>
)
})
六、组件复合写法
组件复合类似于我们在vue框架⾥⾯⽤的组件插槽
import React from 'react'
function Dialog(props){
return(
<div style={{border:`5px solid ${props.color || "green"}`}}>
{/* 相当于vue框架中的匿名插槽 */}
{props.children}
{/* 相当于vue框架中的具名插槽 */}
{props.btn}
</div>
)
}
export default function Composition() {
const confimBtn = (
<button onClick={()=>alert('ok?')}>确认</button>
)
return (
<div>
<h1>组件复合写法</h1>
<Dialog color='pink' btn={confimBtn}>
<h2>小滴课堂</h2>
<p>欢迎欢迎</p>
</Dialog>
</div>
)
}