今天学习了react中的函数子组件的概念,然后在工作中得到了实际应用,很开心,那么好记性不如烂笔头,开始喽~
函数子组件(FaCC )与高阶组件做的事情很相似, 都是对原来的组件进行了加强,类似装饰者。
FaCC,利用了react中children可以是任何元素,包括函数的特性,那么到底是如何进行增强呢?
分两步走
第一步:class FetchDataParent
import * as React from 'react'import { get } from '../../common/fetch'import { handleNotificate } from '@hi-ui/hiui/es/notification'export default class WithRangeData extends React.PureComponent {
constructor (props) {
super(props) this.state = {
data: []
}
}
componentDidMount () {// 从props中接收url,然后制作data,存入到自己的state中,具体处理逻辑,大家不用看
const { url } = this.props
get(url)
.then(res => { if (res && res.status === 200) {
const result = []
res.data.forEach(element => {
const { status, value } = element switch (status) { case 0:
result.push({
name: value,
id: value
}) break
default:
}
}) this.setState({
data: result
})
} else {
handleNotificate({
type: 'erroe',
autoClose: true,
title: '请求出错',
message: `请求出错,原因:${res.message}`
})
}
})
}
render () {
const { children } = this.props
const { data } = this.state// 这里是关键,将自己state中的值,传给children,直接执行了children(), 说明children是个函数
return <div>
{children(data)} </div> }
}第二步:使用上面的父组件,
export default class AccessApply extends React.PureComponent {
render(){
return ( <WithRangeData
url={`${encyclopediaUrl.getPermissionDimensionValues}?id=${range.id}`} >
{
(data) => { return ( <div>
<span>{range.nickname}</span>
<Select
mode='multiple'
list={data}
onChange={(item) => {
console.log('多选结果', item)
}}
/>
</div> )
}
} </WithRangeData> )
}
}
总结:可以看到,函数子组件模式,也是给他的children传递一些数据,与高阶组件很相似。
然而,FaCC不会再去创建一个新的Component,而HOC会创建一个新的Component然后传递props下去。 同时,FaCC这种模式,父组件与子组件的关系比较明显,代码更易读。
高阶组件优点:有完整的生命周期。FaCC中children直接执行,无生命周期。
最后,展示一下react 函数组件如何写Facc:
const ClassNameWrapper = ({ children }) => children('demo-class')// 使用const HeadWithClass = (props) => ( <ClassNameWrapper>
{(class) => <header classNmae={class} ></header>}
</ClassNameWrapper>
)
参考文章:https://segmentfault.com/a/1190000016269347

随时随地看视频