Created
June 15, 2016 04:33
-
-
Save sergiodxa/09fa274d68c929a4059bdb8000c03e49 to your computer and use it in GitHub Desktop.
Ejemplo de usar HOC para extender un componente de React.js
This file contains 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
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); |
This file contains 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
import React from 'react'; | |
import { render } from 'react-dom'; | |
import App from './App.jsx'; | |
render( | |
<App timer={1000} />, | |
document.getElementById('app') | |
); |
This file contains 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
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