高阶组件个人理解其实就是抽离公共逻辑 ,高阶组件英语全称为 Higher-Order Components,简称 HOC,所谓高阶组件,是 React中一种复用逻辑的技巧。高阶组件是一个函数,高阶组件作为一个函数,接收你传入的组件,然后又返回一个新组件给你
简单示例:比如说现在有个餐厅,餐厅有固定餐牌,客人点了什么直接输入序列号,餐厅获取客人的餐桌号和点的餐单等信息,价钱也不一样
高阶组件
javascript
// withTimer
export default function withInfo (Com) {
return function NewCom(props) {
// 必须传序列号,对应的是菜品
if(!props.serial) {
return new Error('请传入序列号')
}
// 这个可以是后台返回的数据
const foodMenu = [
{
id: 1,
food: '辣椒炒肉'
},
{
id: 2,
food: '青椒炒蛋'
},
{
id: 3,
food: '苦瓜炒肉'
}
]
const dotMenu = foodMenu.filter(item => item.id === props.serial)
let backMenu = {
...props
}
if(dotMenu && dotMenu.length > 0) {
backMenu.food = dotMenu[0].food
}
return <Com {...backMenu} />
}
}
父组件
javascript
import React from 'react'
import withInfo from './HOC/withInfo'
import ChildCom3 from './components/ChildCom3'
import ChildCom4 from './components/ChildCom4'
const NewChildCom3 = withInfo(ChildCom3)
const NewChildCom4 = withInfo(ChildCom4)
export default function MyHocStudy() {
const client = [
{
userId: 1,
name: '张三',
serial: 1,
table: 3
},
{
userId: 1,
name: '李四',
serial: 3,
table: 2
}
]
return (
<div>
<NewChildCom3 {...client[0]} />
<NewChildCom4 {...client[1]} />
</div>
)
}
子组件1
javascript
import React from 'react'
export default function ChildCom3(props) {
console.log('cm3', props);
return (
<div>
<h3>ChildCom3-这是在包间-服务等不一样</h3>
<div>
<div>餐品: {props.food}</div>
</div>
</div>
)
}
子组件2
javascript
import React from 'react'
export default function ChildCom3(props) {
console.log('cm4', props);
return (
<div>
<h3>ChildCom4-这是在大厅-服务等不一样</h3>
<div>
<div>餐品: {props.food}</div>
</div>
</div>
)
}