|
| 1 | +import {Component} from 'react'; |
| 2 | +import {h, noop} from './util'; |
| 3 | + |
| 4 | +export interface IInvertedProps { |
| 5 | + children?: (...args) => React.ReactElement<any>; |
| 6 | + onMounted: (el: HTMLElement, comp: React.Component<any>) => void; |
| 7 | + render: (element: React.ReactElement<any>, comp: React.Component<any>) => React.ReactElement<any>; |
| 8 | +} |
| 9 | + |
| 10 | +export type TInvert = (tag: string) => React.ComponentClass<any>; |
| 11 | + |
| 12 | +const defaultRenderProp = (element) => element; |
| 13 | + |
| 14 | +export const invert: TInvert = (tag: keyof React.ReactHTML) => { |
| 15 | + const Inverted = class Inverted extends Component<IInvertedProps, any> { |
| 16 | + static defaultProps = { |
| 17 | + render: defaultRenderProp |
| 18 | + }; |
| 19 | + |
| 20 | + el: HTMLElement = null; |
| 21 | + |
| 22 | + ref = (el) => { |
| 23 | + this.el = el; |
| 24 | + }; |
| 25 | + |
| 26 | + componentDidMount () { |
| 27 | + (this.props.onMounted || noop)(this.el, this); |
| 28 | + } |
| 29 | + |
| 30 | + compnentWillUnmount () { |
| 31 | + this.el = null; |
| 32 | + } |
| 33 | + |
| 34 | + event (name: string, handler: (...args) => void) { |
| 35 | + return (event) => { |
| 36 | + handler(event, this); |
| 37 | + this.forceUpdate(); |
| 38 | + }; |
| 39 | + } |
| 40 | + |
| 41 | + render () { |
| 42 | + const {event} = this; |
| 43 | + const {children, render, ...rest} = this.props; |
| 44 | + const props = { |
| 45 | + ref: this.ref |
| 46 | + }; |
| 47 | + |
| 48 | + for (const name in rest) { |
| 49 | + const value = rest[name]; |
| 50 | + |
| 51 | + if ((name[0] === 'o') && (name[1] === 'n') && (typeof value === 'function')) { |
| 52 | + props[name] = this.event(name, value); |
| 53 | + } else { |
| 54 | + props[name] = value; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + const element = h(tag, props, typeof children === 'function' ? children(this) : children); |
| 59 | + |
| 60 | + return render(element, this); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return Inverted; |
| 65 | +}; |
0 commit comments