简介

很多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 {
//es7语法
//显示在react developer tools中,位于顶部,不写为默认的Timer
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';

// es7语法 
// @TimerEnhance
class App extends Component {
//es7语法 默认state
state = {value: ''};
handleClick = (e) => {
this.setState({value: this.state.value+'new'});
}

render() {
// TimerEnhance中的state,props都会转化为props,并且在App组件中,可以直接调用,如this.props.seconds
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'));