React的开发中经常会遇到hooks写法和Class写法混合开发的情况,那么在这种情况下,如何在class组件中调用customHooks的方法呢?
我的解决办法是使用HOC(高阶组件)。
首先,我们创建一个使用TSX的react工程:yarn create react-app my-app --template typescript
编写我们的hooks:
import { useEffect, useState } from 'react';
export const useTest = () => {
const [state, setState] = useState<number>(0);
useEffect(() => {
console.log('this is useEffect !');
}, [])
return {
state: state,
setState: setState
}
}
接下来编写对应的HOC:
import * as React from 'react'
import {useTest} from './hooks'
export const withHooksHOC : Function = (C: any ) => {
// 值得注意的一点:HOC是一个函数而非组件
return () => {
const { state, setState } = useTest()
return <C setState={setState} state={state} />
}
}
最后,我们来编写对应的组件作为渲染:
import * as React from 'react';
import {withHooksHOC} from './HOC'
interface HocProps {
state: number,
setState: Function
}
class Demo extends React.Component<HocProps> {
render () {
return <div>
{/* 这里的state和setState来自于customhooks */}
<div>{ this.props.state }</div>
<button onClick={() => {
let v = Math.random() * 1000000
this.props.setState(v)
}}>click it</button>
</div>
}
}
export default withHooksHOC(Demo)
在视图直接渲染:
import * as React from 'react';
import Com from './components'
function App() {
return (
<div className="App">
<Com />
</div>
);
}
export default App;