Created
August 28, 2018 07:55
-
-
Save na0x2c6/f7e75c1ecbd32d32825d9427e47e480a to your computer and use it in GitHub Desktop.
HOC Sample 3:Inheritance Inversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function withSubscription(WrappedComponent, selectData) { | |
return class extends WrappedComponent { | |
constructor(props) { | |
super(props) | |
this.handleChange = this.handleChange.bind(this) | |
this.state = { | |
data: selectData(DataSource, props) | |
} | |
} | |
componentDidMount() { | |
DataSource.addChangeListener(this.handleChange) | |
} | |
componentWillUnmount() { | |
DataSource.removeChangeListener(this.handleChange) | |
} | |
handleChange() { | |
this.setState({ | |
data: selectData(DataSource, this.props) | |
}) | |
} | |
render() { | |
return super.render() | |
} | |
} | |
} | |
const Card = ({ card }) => ( | |
<div className="card"> | |
<div className="card-content" style={{ color: card.color }}> | |
{card.name} | |
</div> | |
</div> | |
) | |
class List extends React.Component { | |
render() { | |
return ( | |
<div className="column" | |
style={{ backgroundColor: this.props.list.color }}> | |
<header>{`${this.props.list.name} (id:${this.props.list.id})`}</header> | |
{this.state.data.map((card, idx) => | |
<Card card={card} key={idx} /> | |
)} | |
</div> | |
) | |
} | |
} | |
const ListWithSubscription = withSubscription( | |
List, | |
(DataSource, props) => DataSource.getCards(props.list.id) | |
) | |
class Board extends React.Component { | |
render() { | |
return ( | |
<div className="columns"> | |
{this.state.data.map(list => | |
<ListWithSubscription list={list} key={list.id} /> | |
)} | |
</div> | |
) | |
} | |
} | |
const BoardWithSubscription = withSubscription( | |
Board, | |
(DataSource) => DataSource.getLists() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment