如何使类装饰器与他人可链接?

时间:2019-08-05 09:18:06

标签: javascript reactjs decorator

import React, { createElement, createFactory } from 'react'
import hoistNonReactStatics from 'hoist-non-react-statics'

const universe = {}

const withConnectToOtherComponent = componentName => {

  if (!componentName) throw 'componentName required'

  const hoc = WrappedComponent => props => {

    if (!WrappedComponent.prototype.isReactComponent) {
      return WrappedComponent(props)
    }

    class WrapperComponent extends WrappedComponent {

      componentDidMount() {
        if (universe[componentName]) {
          console.error(universe[componentName])
          throw `componentName must be unique, ${componentName} is in use`
        }

        universe[componentName] = this
        this.connect = name => {
          if (Object.prototype.toString.call(name) === '[object String]') {
            return universe[name]
          } else if (Object.prototype.toString.call(name) === '[object Array]') {
            const ref = {}
            for (const _name of name) {
              ref[_name] = universe[_name]
            }
            return ref
          } else {
            return universe
          }
        }

        if (WrappedComponent.prototype.componentDidMount) {
          WrappedComponent.prototype.componentDidMount.apply(this, arguments)
        }
      }

      componentWillUnmount() {
        delete universe[componentName]
        if (WrappedComponent.prototype.componentWillUnmount) {
          WrappedComponent.prototype.componentWillUnmount.apply(this, arguments)
        }
      }

    }

    return createElement(WrapperComponent, props)

  }

  return hoc

}

export default withConnectToOtherComponent
@recompose.withProps({
  test: true,
})
@recompose.withProps({
  test1: true,
})
@onClickOutside
@withConnectToOtherComponent('master')
class Root extends Component {
  state = {
    list: []
  }

  handleClickOutside = () => {
    console.log(this)
  }

  onClick = () => {
    console.log(this)
    // this.wormhole('slave').setState({ buttonName: Date.now() })
  }

  render() {
    return (
      <>
        <div>Root</div>
        <button onClick={this.onClick}>Root</button>
        <div>{this.state.list.map((item, itemIdx) => <div key={itemIdx}>{item}</div>)}</div>
        <ChildComp />
      </>
    )
  }
}

看起来我的兄弟姐妹onClickOutside无法正常工作。

0 个答案:

没有答案