React.createFactory
factoryFunction createFactory(
string/ReactClass type
)
复制代码
上面函数返回一个用于生成给定类型的ReactElement的函数,相似于 React.createElement。对于type参数能够是html标签名字(例如:“div”,“li”, 运行之后生成一个 jsx 对象html
建立一个 ulreact
var child1 = React.createElement('li', null, 'First Text Content');
var child2 = React.createElement('li', null, 'Second Text Content');
var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
ReactDOM.render(root, document.getElementById(content));
复制代码
先介绍基本用法,而后介绍和 hoc 结合在一块儿使用bash
我最近写组件的时候 要给全部的页面加上返回的主页的头,再想怎么最省事。懒病发做app
// Layout 是头部组件
< Layout>{this.props.children}</Layout>
复制代码
可是每一个页面都要加 layout 头,太烦了太烦了函数
import React, { Component } from 'react'
// Component.js
class App extends Component {
render () {
return (
<Layout/>
{this._render()}
</Layout>
)
}
}
}
export default Hoc App
// 调用
import Component from './Component'
class Home extends Component {
...
_render () => hello
}
复制代码
这样也是 ok 的但感受总有点奇怪没有 render 方法ui
import React, { Component, createFactory } from 'react'
import { compose } from 'recompose'
const app = (BaseComponent) => {
return class extends Component {
handleClick = () => {
this.props.history.goBack('/home')
}
render () {
return <div>
<Layout>
<BaseComponent {...this.props} {...this.state} />
<Layout/>
</div>
}
}
}
// const Hoc = (c) => createFactory(app(c))
export default compose(
createFactory, app
)
// route 这边能够直接这么调用
import { Hoc } from 'lib'
const routes = [
{
title: '首页',
path: '/home',
component: Hoc(Home),
exact: true
}
]
复制代码
这里我为什么用 createFactory 这么包一层呢,正常咱们不包的话用的时候估计要这样使用this
const Button = Hoc(<BaseComponent />) <Button>1234</Button> 复制代码
这样也是 ok 的,可是你要多个变量来接收,对于取名强迫症的我是没法接受的,特别有不少路由的状况下,因此综上对比方法三最好用spa
这个小技巧只是我无心中发现的,估计不少人都已经用上了甚至。可是我仍是小小的总结一下,😆😆code