项目作者: cahnory

项目描述 :
React component factory factory
高级语言: JavaScript
项目地址: git://github.com/cahnory/create-react-factory.git
创建时间: 2017-02-09T14:43:01Z
项目社区:https://github.com/cahnory/create-react-factory

开源协议:

下载


create-react-factory

create-react-factory create a factory for your react component. It allows you to:

  • compose multiple high order components
  • set a custom component to render using the component property

Installation

  1. npm install create-react-factory

Usage

  1. // Underline.js
  2. import React from 'react'
  3. import createReactFactory from 'create-react-factory'
  4. export const Underline = ({component: Component = 'div', style = {}, ...props}) => (
  5. <Component style={{...style, textDecoration: 'underline'}} {...props} ></Component>
  6. )
  7. export default Underline
  8. export const factory = createReactFactory(Underline)
  1. // Strong.js
  2. import React from 'react'
  3. import createReactFactory from 'create-react-factory'
  4. export const Strong = ({component: Component = 'div', style = {}, ...props}) => (
  5. <Component style={{...style, fontWeight: 'bold'}} {...props} ></Component>
  6. )
  7. export default Strong
  8. export const factory = createReactFactory(Strong)
  1. // Red.js
  2. import React from 'react'
  3. import createReactFactory from 'create-react-factory'
  4. const Red = ({component: Component = 'div', style = {}, ...props}) => (
  5. <Component style={{...style, color: 'red'}} {...props} ></Component>
  6. )
  7. export default Red
  8. export const factory = createReactFactory(Red)
  1. // RedStrongUnderline.js
  2. import {factory as strongFactory} from './Strong'
  3. import {factory as redFactory} from './Red'
  4. import Underline from './Underline'
  5. export const RedStrongUnderline = strongFactory(redFactory(Underline))
  6. export default RedStrongUnderline
  1. import React from 'react'
  2. import {render} from 'react-dom'
  3. import Rsu from './RedStrongUnderline'
  4. render(<ul><Rsu component="li">Hello World!</Rsu></ul>, document.getElementById('root'))
  5. // output:
  6. // <ul>
  7. // <li style="color: red; font-weight: bold; text-decoration: underline;">
  8. // Hello World!
  9. // </li>
  10. // </ul>

Why?

Because with the “traditional” factory approach, the component property is overridden by the Component passed to the factory. Thus it become impossible to set a different component to render.

License

MIT