我有一个函数,它接受一个 React 组件并部分应用它的 props。这用于例如为组件提供来自消费者的主题。
它基本上转换了这个 <FancyComponent theme="black" text="blah"/>
对此<AlreadyFanciedComponent text="blah"/>
,它与 theme
是同一组件已经提供。
我不知道如何输入它。
下面是一些抛出 TypeScript 错误的工作代码:
import * as React from "react";
import * as ReactDOM from "react-dom";
import { ComponentType } from "react";
type Theme = {theme: string};
function preTheme<TProps extends Theme>(WrappedComponent: ComponentType<TProps>) {
return React.forwardRef<typeof WrappedComponent, TProps>((props: TProps, ref) => {
// here could be a Consumer
return <WrappedComponent theme={props.theme} ref={ref} {...props} />
})
}
const ThemedP: React.FC<{theme: string, text: string}> = props => <p className={props.theme}>{props.text}</p>;
const PreThemedP = preTheme(ThemedP);
ReactDOM.render(<PreThemedP text={"Here be useless text"}/>, document.getElementById('root'));
错误是:Property 'theme' is missing in type '{ text: string; }' but required in type '{ theme: string; text: string; }'
最佳答案
您需要Omit
包装组件的 props 中的 theme
属性:
return React.forwardRef<typeof WrappedComponent, Omit<TProps, "theme">>(...);
关于javascript - 如何输入其 props 被部分应用的 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61267895/