简介
很多react
相关的包都有这样的语法export default SomeComponent(App);
,我们自己也可以创建,以下是一个小demo.
It’s no longer possible to use React mixin mechanism for components written in ES6.
参考网站:react-and-es6
Timer.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import React, { Component } from 'react';
export const TimerEnhance = Compose => class Timer extends React.Component { static displayName = 'ComponentEnhancedWithIntervalHOC'; static defaultProps = { name: 'test', number: 3}; constructor(props) { super(props); this.state={seconds: 0}; } componentDidMount() { this.interval = setInterval(this.tick.bind(this), 1000); }
componentWillUnmount() { clearInterval(this.interval); }
tick() { this.setState({ seconds: this.state.seconds + 1000 }); } render() { return ( <div> <Compose {...this.state} {...this.props}/> <h1>TimerEnhance</h1> </div> ); } }
|
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import React, { Component } from 'react'; import { TimerEnhance } from './Timer';
class App extends Component { state = {value: ''}; handleClick = (e) => { this.setState({value: this.state.value+'new'}); }
render() { console.log(this.props,this.state); return ( <div> <h1>Test: {this.props.seconds}</h1> <button onClick={this.handleClick} >Click {this.state.value}</button> </div> ); } }
export default TimerEnhance(App);
|
index.js
1 2 3 4
| import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.querySelector('#root'));
|