我这个问题已经存在了很长时间了,我的想法已经用光了。
我想创建一个HoC,它将向原始组件添加一些道具(函数和字符串)。到目前为止,我有这个:
装饰器:
import * as React from "react";
export interface TestDecoratorProps {
sayHello: () => void;
}
const withTestDecorator = <P extends TestDecoratorProps>(
Component: React.ComponentType<P>,
): any => (props: Pick<P, Exclude<keyof P, keyof TestDecoratorProps>>) => {
const sayHello = () => {
console.log("hello");
};
return <Component {...props as P} sayHello={sayHello} />;
};
export default withTestDecorator;
用法:
import * as React from "react";
import withTestDecorator, { TestDecoratorProps } from "@decorators/TestDecorator";
interface Props extends TestDecoratorProps {
children: React.ReactNode;
}
@withTestDecorator
class Paragraph extends React.Component<Props> {
public componentDidMount() {
this.props.sayHello();
}
public render() {
return <p>{this.props.children}</p>;
}
}
export default Paragraph;
并实施:
class Application extends React.Component {
public render(): React.ReactNode {
return (
<Provider store={store}>
<Paragraph>Hello</Paragraph>
</Provider>
);
}
}
我的问题是,在实现过程中,Paragraph
引发错误,指出需要sayHello
道具。我该怎么办?
我正在使用TypeScript 3.4.3和React 16.8.6。