fre 新突破,class 与 hooks 混用

如题,原由是 rasmus 提交的一个 demoreact

codesandbox.io/s/fre-demo-…git

你们都知道,fre 是一个纯 hooks 的 react like 框架,也正是由于这个缘由,它才能够作到 1kb,才能够无痛搞定异步渲染github

可是若是有一种方式能够绝不费力的实现 class 的话,那顺手的事,支持一下也无妨框架

import { h, render } from 'fre'
import { Component, useComponent } from './fre-component'

class Counter extends Component {
  constructor (props) {
    super(props)
    this.state = { count: 0 }
  }

  render () {
    const { count } = this.state
    const setCount = count => this.setState({ count })

    return (
      <div> {count} <button onClick={() => setCount(count + 1)}>+</button> <button onClick={() => setCount(count - 1)}>-</button> </div>
    )
  }
}

Counter = useComponent(Counter)

render(<Counter />, document.body) 复制代码

如题,原理很简单,就是将一个 class 变成 function 组件,这个作法和 react 是相反的,react 是在 class 的基础上实现 hooks 的 API,而 fre 是在 hooks 的基础上,实现 class 的 API异步

fre 的作法带来了新的突破: class 和 hooks 的混用ide

由于这个 class 的 render 方法实际上是和 hooks 对等的,他只是换了层皮而已this

因此你在 render 方法里使用 hooks 彻底没有影响idea

同时,也解决了 hooks 没法使用 HOC 的问题spa

这是一个很是有趣的 idea,也是至今为止,fre 第一次脱离 react 而主动发现的兴奋♂ 点code

我如今还在思考,是否须要内置到 fre 中,可是我以为这个实现不须要 fre 内部作什么事情,暂时我提倡你们使用 fre 本身改造适合本身的 class 组件

最后放 fre 的 github 地址:github.com/132yse/fre

欢迎 star 与试用,更欢迎一块儿来寻找突破 ^_^

相关文章
相关标签/搜索