react 函數子組件(Function ad Child Component)

今天學習了react中的函數子組件的概念,而後在工做中獲得了實際應用,很開心,那麼好記性不如爛筆頭,開始嘍~html

函數子組件(FaCC )與高階組件作的事情很類似, 都是對原來的組件進行了增強,相似裝飾者。

FaCC,利用了react中children能夠是任何元素,包括函數的特性,那麼究竟是如何進行加強呢?react

分兩步走

第一步: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(){
    // WithRangeData裏的children是一個函數,接收父組件給的data,並return出本身想要的任何東西。
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傳遞一些數據,與高階組件很類似。segmentfault

然而,FaCC不會再去建立一個新的Component,而HOC會建立一個新的Component而後傳遞props下去。 同時,FaCC這種模式,父組件與子組件的關係比較明顯,代碼更易讀。數組

高階組件優勢:有完整的生命週期。FaCC中children直接執行,無生命週期。app

 

最後,展現一下react 函數組件如何寫Facc:函數

const ClassNameWrapper = ({ children }) => children('demo-class') // 使用
 const HeadWithClass = (props) => ( <ClassNameWrapper> {(class) => <header classNmae={class} ></header>}
  </ClassNameWrapper>
)

 

參考文章:https://segmentfault.com/a/1190000016269347學習

原文出處:https://www.cnblogs.com/yadiblogs/p/10197598.htmlfetch

相關文章
相關標籤/搜索