iT邦幫忙

1

React Components 怎麼互相轉換?

標題不知怎麼表達,意思有點不明,抱歉。

大大們好 最近剛摸React 目前在做React Router v4的Modal Gallery範例

https://reacttraining.com/react-router/web/example/modal-gallery

目前看到的React Component 有兩種寫法

一種是 High Order

class App extends React.Components{
    render(){
        return(
            <div>
            </div>
        )
    }
}

還有一種比較精簡的

const app = () => {

    return(
        <div>
        </div>
    )
}

我想問說 怎麼把 Modal Gallery範例 裡的

const Modal = ({ match, history }) => {
   //略
  return (
    <div
        // 略
    </div>
  )
}

轉成High Order Components的寫法?
我不知道{ match, history } 該放到哪個位置,因為match,跟history使從外部傳進的變數,不知道High Order Components 是放在哪邊接收match,跟history

我有自己嘗試做看看,但好像不太對呢

class Model extends React.Components{
    constructor(){
        this.state(
            match:match,
            history:history
        )
    }
    render(){
        return(
            <div>
            </div>
        )
    }
}
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
eugenechen
iT邦新手 5 級 ‧ 2018-06-21 10:07:23

參考:https://medium.com/@yujiechen0514/%E9%87%8D%E6%A7%8B-react-component-%E9%82%81%E5%90%91-prue-container-component-%E5%92%8C-hoc-3df5adf35aaf

Higher order component 是一個函數,它輸入一個 component,回傳一個新的 component。

// HOC:用函數產生器(function generator)的模式
function withSome({ match, history }) {
  return function(WrappedComponent) {
    return class extends React.Component {
      render() {
        return <WrappedComponent {...this.props} match={match} history={history} />;
      }
    }; 
  }
}

// 使用HOC
const WrappedModel = withSome({match, history})(Model);

render() {
    return <WrappedModel modelProperty="value1"/>
}

當使用 <WrappedModel/> 時, <Model/> 除了 modelProperty外,會多收到 matchhistory 的屬性

Luis-Chen iT邦新手 4 級 ‧ 2018-06-22 22:35:48 檢舉

哈 好久的文了

不過還是感謝大大 解答

我要發表回答

立即登入回答