高阶组件
高阶组件是参数为组件,返回值为新组件的函数(建议大家先回顾一下ts中的泛型的用法)
视频教程地址
- 我们定义一个函数withLee,它的参数是一个组件,并把这个组件返回
//import React, {Component, ComponentType} from "react"; 不要忘记导入依赖
function withLee<T>(Wrap: ComponentType<T>): ComponentType<T> {
return class extends Component<T> {
render() {
return <Wrap {...this.props}/>;
}
}
}
-
定义一个组件,使用高阶组件重新生成一个新的组件
interface IProps { name?: string } class Lee extends Component<IProps> { render() { return ( <> {this.props.name} </> ) } } export default withLee<IProps>(Lee)
-
使用组件
import React from 'react'; import Lee from "./withLee"; function App() { return ( <> <Lee name='lee'/> </> ); } export default App;