Skip to content

Instantly share code, notes, and snippets.

@sergiodxa
Created June 15, 2016 04:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sergiodxa/09fa274d68c929a4059bdb8000c03e49 to your computer and use it in GitHub Desktop.
Save sergiodxa/09fa274d68c929a4059bdb8000c03e49 to your computer and use it in GitHub Desktop.
Ejemplo de usar HOC para extender un componente de React.js
import React, { Component } from 'react';
import setIntervalHOC from './set-interval.js';
class App extends Component {
static propTypes = {
timer: PropTypes.number,
}
static defaultProps = {
timer: 500,
}
state = {
amount: 0,
}
componentDidMount() {
this.props.setInterval(
this.tick.bind(this),
this.props.timer
);
}
tick() {
this.setState({
amount: this.state.amount + 1,
});
}
render() {
return (<div>{this.state.amount}</div>);
}
}
export default setIntervalHOC(App);
import React from 'react';
import { render } from 'react-dom';
import App from './App.jsx';
render(
<App timer={1000} />,
document.getElementById('app')
);
import React, { Component } from 'react';
function setIntervalHOC(WrappedComponent) {
return class WithSetInterval extends Component {
componentWillMount() {
this.intervals = [];
}
setInterval(..args) {
this.intervals.push(setInterval.apply(null, args));
}
componentWillUnmount() {
this.intervals.forEach(clearInterval);
}
render() {
return (
<WrappedComponent
setInterval={this.setInterval.bind(this)}
{...this.props}
/>
);
}
}
}
export default setIntervalHOC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment