把组件放在另外一个组件的 render 方法里面, 并且利用了 {...this.props} {...this.state} 这些 JSX 展开属性
对比下2种代码:
原始方式:
<!DOCTYPE html> <html> <head> <script src="../build/react.js"></script> <script src="../build/react-dom.js"></script> <script src="../build/browser.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> var intervalMixin = { componentDidMount: function(){ this.arr = []; }, setInterval: function(callback, interval){ var token = setInterval(callback, interval); this.arr.push(token); return token; } } var S = React.createClass({ mixins: [intervalMixin], getInitialState: function(){ return { num: 0 } }, componentDidMount: function(){ this.setInterval( ()=> this.setState({num: this.state.num+1}), 1000); }, render: function(){ return <div> {this.state.num} </div> } }); ReactDOM.render( <S q="bb" />, document.getElementById(‘example‘) ); </script> </body> </html>
高阶组件调用:
<!DOCTYPE html> <html> <head> <script src="../build/react.js"></script> <script src="../build/react-dom.js"></script> <script src="../build/browser.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> // 注意参数 Com 需要第1个字母大写 const Enhance = Com => { const Res = class extends React.Component { // 这种写法 ES6 不支持 // static defaultProps = { // autoPlay: false, // maxLoops: 10, // }; // 注意这里有分号 constructor(props, context) { super(props, context); this.state = { time: 0 }; } static a(){ } componentDidMount() { setInterval(this.tick.bind(this), 1000); } tick() { this.setState({ time: this.state.time + 1 }); } render() { // ...this.props 相当于 text = {this.props.text} // ...this.state 相当于 time = {this.state.time} return <Com {...this.props} {...this.state} />; } } Res.defaultProps = { text: ‘hello world‘ }; return Res; } class Time extends React.Component { render() { return <div> {this.props.text} {this.props.time} </div>; } } /* 注意这里 A 的值必须为大写, 不能写成 这种形式 ReactDOM.render( Enhance(Time), document.getElementById(‘example‘) ); ) */ var A = Enhance(Time); ReactDOM.render( <A />, document.getElementById(‘example‘) ); </script> </body> </html>
参考地址:
Mixins Are Dead. Long Live Composition
时间: 2024-10-07 06:38:44