Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.