typescript react hoc的问题

现在想实现一个hoc,功能是给组件加上统一的生命周期。如果不使用typescript很简单。
//Main
clipboard.png
//HOCTest
clipboard.png

如果使用typescript
clipboard.png
clipboard.png

报错
clipboard.png

阅读 4k
3 个回答

老老实实用HocTest()这样的方式应该是可行的吧

interface WithLogProps {
  time: string
}

function withLog(options: Partial<WithLogProps>) {
  return <P extends {}>(
    WrappedComponent: ComponentType<P>
  ): ComponentClass<any> =>
    class extends Component<P> {
      componentDidMount() {
        const { time } = options
        console.log(`log ${time}`)
      }
      render() {
        return <WrappedComponent {...this.props} />
      }
    }
}
function withLogOrig<P extends {}>(Com: ComponentType<P>) {
  return class extends Component<P> {
    componentDidMount() {
      console.log('log')
    }
    render() {
      return <Com {...this.props} />
    }
  }
}
interface IonicExampleProps {
  value: string
}
interface State {}

class IonicExample extends Component<IonicExampleProps, State> {
  render() {    
    return <div>'我是被包裹的'</div>
  }
}
export default withLog({ time: '20' })(IonicExample)

测试这样是可行的啊

可以这样写,不过ts能被extend的表达式的类型有点麻烦

function HOCTest<C extends new(...args: any[])=>{}>(target: C): C {
    return class extends target {

    }
}

你都已经在用react了,不如抛弃extend

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题