我正在尝试创建一个装饰器,该装饰器接受来自React的参数。上下文提供程序,如果我想创建HOC,这很容易:
interface DashboardProps {
user: User;
}
class Dashboard extends React.Component<DashboardProps> {
render() {
return (<span>{this.props.user.name}</span>);
}
}
function withUser(WrappedComponent) {
return class extends React.Component {
render() {
return (
<UserContext.Consumer>
{user => <WrappedComponent user={user} {...this.props}>}
</UserContext.Consumer>
);
}
}
}
export default withUser(Dashboard);
但是我不确定如何像装饰器一样编写它:
@withUser
class Dashboard ...
答案 0 :(得分:0)
打字稿中的类装饰器的类型如下:
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
这意味着类装饰器函数必须返回相同类型的组件,否则不返回任何内容。
function withUser(WrappedComponent): void {
return class extends React.Component {
render() {
return (
<UserContext.Consumer>
{user => <WrappedComponent user={user} {...this.props}>}
</UserContext.Consumer>
);
}
} as unknown as void;
}