JSFiddle - React, Tailwind, and code Playground
by treekey
HTML
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<h1>DataProvider HOC Example </h1>
<hr>
<div id="app" />
Babel + JSX
function DataProvider(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props)
this.state = { userName: undefined, userEmail: undefined }
}
componentDidMount() {
const data = this.apiGetData()
this.setState({ userName: data.userName, userEmail: data.userEmail })
}
apiGetData(){
return {
userName: 'hao',
userEmail: '[email protected]',
}
}
render() {
return (
<WrappedComponent
{
// 原本 Component 的 props
...this.props
}
data={
// HOC 提供的 props, 可能會有命名重複的問題
this.state
}
/>
)
}
}
}
const MyComponent = ({ data }) => (
// 這裡只預期接收 data 的 props, 但是並不會知道 data 是從哪來得來的
<div>
<h1>Hello, { data.userName }</h1>
<p>{ data.userEmail }</p>
</div>
)
const MyComponentWithData = DataProvider(MyComponent)
const App = () => (
<div>
<MyComponentWithData />
</div>
)
ReactDOM.render( <App /> , document.getElementById('app'))