javascript - 如何输入其 props 被部分应用的 React 组件?

标签 javascript reactjs typescript

我有一个函数,它接受一个 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; }'

Here it is in a playground.

最佳答案

您需要Omit包装组件的 props 中的 theme 属性:

return React.forwardRef<typeof WrappedComponent, Omit<TProps, "theme">>(...);

关于javascript - 如何输入其 props 被部分应用的 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61267895/

相关文章:

reactjs - 需要有关 ReactNative、Redux 和 Navigator 的一些概念的帮助

JavaScript:将对象数组转换为 HashMap

html - Angular2 将来自服务器的 html 包含到一个 div 中

javascript - 如何从图像创建/保存裁剪后的图像? (将图像转换为base64)

javascript - 检查模态是否打开时出现 NoSuchElementError

javascript - 向提交按钮添加点击事件,然后提交表单

javascript - 从 typescript 中的 &lt;input&gt; 元素获取值

javascript - OpenLayers:放大或缩小后被破坏的特征重新出现

css - .css 未加载,因为其 MIME 类型 “text/html” 不是 “text/css” 。和 SyntaxError : expected expression, 得到 '<'

javascript - 如何在 REACT 中保持和循环数组中 HTML 元素的样式?