项目作者: aleclarson

项目描述 :
Yield for render props
高级语言: TypeScript
项目地址: git://github.com/aleclarson/yender.git
创建时间: 2018-09-20T14:51:28Z
项目社区:https://github.com/aleclarson/yender

开源协议:

下载


yender

Use generator functions to harness the power of “render props” while avoiding “callback hell”.

Why call it “yender”? It’s a portmanteau of “yield” and “render”

Note: This is essentially a mirror of epitath with Typescript support (and a better name, imo).

Example

  1. import {yender} from 'yender'
  2. const HelloWorld = yender(function* () {
  3. const {foo} = yield <Foo ></Foo>
  4. console.log(foo) // => true
  5. return 'Hello world'
  6. })
  7. const element: JSX.Element = <HelloWorld ></HelloWorld>

Where Foo is the following:

  1. import {Render} from 'yender'
  2. const Foo = (props: FooProps) =>
  3. props.children({ foo: true })
  4. interface FooProps {
  5. // Children must be optional.
  6. children?: Render<{ foo: true }>
  7. }

In the HelloWorld generator function, the foo variable returned by yield <Foo ></Foo> is untyped (see here).

For type safety, we need to use explicit types:

  1. import {RenderProps as P} from 'yender'
  2. const HelloWorld = yender(function* () {
  3. // `typeof` is required because `Foo` is a function, not a class
  4. const {foo}: P<typeof Foo> = yield <Foo ></Foo>
  5. const bar: string = foo // [ts] Type 'true' is not assignable to type 'string'.
  6. console.log(foo) // => true
  7. return 'Hello world'
  8. })

The @yender decorator

Component classes are supported, too!

  1. import {Component} from 'react'
  2. import {yender} from 'yender'
  3. @yender
  4. class HelloWorld extends Component {
  5. *render() {
  6. const {foo} = yield <Foo ></Foo>
  7. return 'Hello ' + this.props.world
  8. }
  9. }
  10. // Without decorators
  11. yender(HelloWorld)