typescript - Typescript HOC - 需要 React 组件上的道具
问题描述
啊,TS。我无法强制 HOC 要求所有使用它的组件包含属性。这就是我所拥有的:
interface ExpectedComponentProps {
requiredProp: string;
[other: string]: any;
}
const withRequiredProp = function<OriginalProps extends ExpectedComponentProps>(
WrappedComponent: React.ComponentType<OriginalProps>
) {
// here I know requiredProp is defined for the component
}
示例用法:
const MyNewComponent = withRequiredProp(MyComponent);
// this should be valid
// <MyNewComponent requiredProp="hello" />
// this should throw a TS error
// <MyNewComponent />
但是,它并没有像我期望的那样强制执行 requiredProp 。我怎么弄乱了这里的语法?
解决方案
这似乎有效
function withRequiredProp<C extends React.ComponentType<any>>(
Component: C,
): React.ComponentType<ExpectedComponentProps> {
return Component //we just return the argument but we said it was
// React.ComponentType<ExpectedComponentProps>
}
const MyComponent: React.FC = () => (
<div>test</div>
);
const MyNewComponent = withRequiredProp(MyComponent);
现在,MyComponent
不强制执行 requiredProp。但MyNewComponent
确实如此。
<MyComponent /> //OK
<MyNewComponent /> //error
<MyNewComponent requiredProp="hello" /> //OK
推荐阅读
- html - 如何将img放在div的右下角?
- asp.net-mvc - Azure 在使用 IConfigurationBuilder.Build 时出现 HTTP 500 错误
- typescript - 为什么我们不在 NgRx 中直接到达状态?
- excel - VBA 按名称从大到小列出参数
- haskell - 使用 Haskell ADT 成员的构造函数作为类型
- javascript - 如果使用 imacros Javascript 有附加值,该怎么办?
- html - SVG 符号内的样式节点是否未定义行为?
- python - len 容器更改,没有这样的元素 无法找到元素。刮tripadvisor评论
- codeblocks - Code::Blocks 有自己版本的#define 吗?
- python - 与子进程交互的问题