|
| 1 | +--- |
| 2 | +id: docs-mixins |
| 3 | +title: Mixins |
| 4 | +layout: docs |
| 5 | +prev: advanced-components.html |
| 6 | +next: api.html |
| 7 | +--- |
| 8 | + |
| 9 | +Mixins allow code to be shared between multiple React components. They are pretty similar to mixins |
| 10 | +in Python or traits in PHP. Let's look at a simple example: |
| 11 | + |
| 12 | +```javascript |
| 13 | +var MyMixin = { |
| 14 | + getMessage: function() { |
| 15 | + return 'hello world'; |
| 16 | + } |
| 17 | +}; |
| 18 | + |
| 19 | +var MyComponent = React.createClass({ |
| 20 | + mixins: [MyMixin], |
| 21 | + render: function() { |
| 22 | + return <div>{this.getMessage()}</div>; |
| 23 | + } |
| 24 | +}); |
| 25 | +``` |
| 26 | + |
| 27 | +A class can use multiple mixins, but no two mixins can define the same method. Two mixins can, however, |
| 28 | +implement the same [lifecycle method](component-lifecycle.html). In this case, each implementation will be invoked one after another. |
| 29 | + |
| 30 | +The only exception is the `shouldComponentUpdate` lifecycle method. This method may only be implemented once |
| 31 | +(either by a mixin or by the component). |
| 32 | + |
| 33 | +```javascript |
| 34 | +var Mixin1 = { |
| 35 | + componentDidMount: function() { |
| 36 | + console.log('Mixin1.componentDidMount()'); |
| 37 | + } |
| 38 | +}; |
| 39 | + |
| 40 | +var Mixin2 = { |
| 41 | + componentDidMount: function() { |
| 42 | + console.log('Mixin2.componentDidMount()'); |
| 43 | + } |
| 44 | +}; |
| 45 | + |
| 46 | + |
| 47 | +var MyComponent = React.createClass({ |
| 48 | + mixins: [Mixin1, Mixin2], |
| 49 | + render: function() { |
| 50 | + return <div>hello world</div>; |
| 51 | + } |
| 52 | +}); |
| 53 | +``` |
| 54 | + |
| 55 | +When `MyComponent` is mounted into the page, the following text will print to the console: |
| 56 | + |
| 57 | +``` |
| 58 | +Mixin1.componentDidMount() |
| 59 | +Mixin2.componentDidMount() |
| 60 | +``` |
| 61 | + |
| 62 | +## When should you use mixins? |
| 63 | + |
| 64 | +In general, add a mixin whenever you want a component to share some utility methods, public interface, |
| 65 | +or lifecycle behavior. Often it's appropriate to use them as you would use a superclass in another OOP language. |
0 commit comments