Last active
April 29, 2018 05:44
-
-
Save cjkihl/e1f7240938bbfdf0ea4e36c93018830c to your computer and use it in GitHub Desktop.
React Mixin Example
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
| // Simple mixin that listens to mouse events and | |
| // sets the state everytime the mouse position changes | |
| var MousePosMixin = { | |
| getInitialState() { | |
| return { mouseX: 0, mouseY: 0 } | |
| }, | |
| onMouseMove(e) { | |
| this.setState({ mouseX: e.clientX, mouseY: e.clientY }); | |
| }, | |
| componentDidMount() { | |
| window.addEventListener("mousemove", this.onMouseMove); | |
| }, | |
| componentWillUnmount() { | |
| window.removeEventListener("mousemove", this.onMouseMove); | |
| } | |
| }; | |
| // This component will now have mouseX and mouseY in the state | |
| var MyComponent = React.createClass({ | |
| mixins: [MousePosMixin], | |
| render() { | |
| return (<span>Mouse X: {this.state.mouseX} Mouse Y: {this.state.mouseY}</span>); | |
| } | |
| }); | |
| ReactDOM.render( | |
| <MyComponent />, | |
| document.getElementById('container') | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment