Share codes In React
mixins -> HOC -> Render Props
GO Back To 2015
import React from 'react'
import ReactDOM from 'react-dom'
const App = React.createClass({
getInitialState() {
return { x: 0, y: 0 }
},
handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
})
},
render() {
const { x, y } = this.state
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
<h1>The mouse position is ({x}, {y})</h1>
</div>
)
}
})
ReactDOM.render(<App/>, document.getElementById('app'))
Mixins
- Using React.createClass
- Combined Mutiple Mixins Lifecycle
- You can share some codes!
import React from 'react'
import ReactDOM from 'react-dom'
const MouseMixin = {
getInitialState() {
return { x: 0, y: 0 }
},
handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
})
}
}
const App = React.createClass({
mixins: [ MouseMixin ],
render() {
const { x, y } = this.state
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
<h1>The mouse position is ({x}, {y})</h1>
</div>
)
}
})
ReactDOM.render(<App/>, document.getElementById('app'))
ES6 Class do not support mixins
Mixins Problems
- React decide to use ES6 Class
- ES6 Class do not support mixins anymore
- State you do not know where come from
- State maybe overwritten by other mixins
HOC
High-Order Components
Come From Hign-order functions
- Takes one or more functions as arguments
- Returns a function as its result
Change to Hign-order Components
- Takes one or more component as arguments
- Returns a component as its result
const hoc1 = (Component) => {
return class extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Component {...this.props} {...this.state} />
}
};
}
const EnhancedComponent = ho1(Component);
High-order components problems
- Props you do not know where come from
- Props maybe overwritten by other mixins
- Static Composition
Render Props
Use Props to Render what u want
Title Text
Subtitle
Share Codes In React
By Stanney Yen
Share Codes In React
- 256