CPPAlien / JS-QA

前端知识问答
0 stars 0 forks source link

mixins in React,Vue #28

Open CPPAlien opened 4 years ago

CPPAlien commented 4 years ago

由于是 配合 React.createClass 使用的,而此方法已经在 React 16 版本上被移除,所以不再支持

import React from 'react';
var SomeMixin = {
  doSomething() {
  }
};
const Contacts = React.createClass({
  mixins: [SomeMixin],
  handleClick() {
    this.doSomething(); // use mixin
  },
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }
});
export default Contacts;
var mixin = {
  created: function () {
    console.log('mixin hook called')
  }
}

new Vue({
  mixins: [mixin],
})
CPPAlien commented 4 years ago

React 引入 class 后,使用 高阶组件的方式做代码复用

//@flow

import React from 'react';
//1
export var IntervalEnhance = ComposeComponent => class extends ComposeComponent {
    // 2
    static displayName = 'ComponentEnhancedWithIntervalHOC';

    constructor(props) {
        super(props);
        this.state = {
            seconds: 0
        };
    }
    // 3
    componentDidMount() {
        this.interval = setInterval(this.tick.bind(this), 1000);
    }
    // 3
    componentWillUnmount() {
        clearInterval(this.interval);
    }

    tick() {
        this.setState({
            seconds: this.state.seconds + 1000
        });
    }

    render() {
        return (
            // 4
            <ComposeComponent {...this.props} {...this.state} />
        );
    }
}
import React from 'react';

import {IntervalEnhance} from './IntervalEnhance';

class CartItem extends React.Component {

    render() {
        return (
            <article className="row large-4">

                <p className="large-12 column" >
                    <strong>Time elapsed for interval: </strong>
                    {this.props.seconds} ms
                </p>

            </article>
        );
    }
}

export default IntervalEnhance(CartItem);
CPPAlien commented 4 years ago

render props

render() {
    return (
      <div>
        <ToggleRenderProps render={()=>(
            <div>
            <h1>tut list</h1>
            <button>隐藏/显示</button>
            </div>
        )}/>

      </div>
    )
  }
  render() {
      const { render} = this.props;
    return (
      <div>
        {render()}
      </div>
    )
  }

使用 PureComponent 可能会造成问题,因为 render 内容改变,并不会触发更新