簡體   English   中英

我可以在 React 的 JSX / TSX 中直接調用 HOC 嗎?

[英]Can I call HOC directly from within JSX / TSX in React?

我在 TypeScript 中有一個 React HOC,但是當我從 TSX 組件render方法中調用它時它似乎不起作用。 下面是一個例子:

export class HelloWorldComponent extends React.Component<{}, {}> {
    public render(): JSX.Element {
        return <div>Hello, world!</div>;
    }
}

export const withRedText = (Component) => {
    return class WithRedComponent extends React.Component<{}, {}> {
        public render(): JSX.Element {                
            return (
                <div style={{color: "red"}}>
                    <Component {...this.props} />
                </div>
            );
        }
    };
}; 

export const HelloWorldComponentWithRedText = withRedText(HelloWorldComponent);

我從這樣的父 JSX 文件中調用它:

public render(): JSX.Element {
    return (
       <div>
           Test #1: <HelloWorldComponent/>
           Test #2: <HelloWorldComponentWithRedText />
           Test #3: { withRedText(<HelloWorldComponent />) }
       </div>
    )
}

第一個和第二個測試按預期工作——第二個中的文本是紅色的。 但第三行什么都不渲染。 我預計第二行和第三行是相同的。

當我使用調試器逐步完成它時,測試 #2 的參數是HelloWorldComponent類型的 Component ,但測試 #3 看到的是Component = Object {$$typeof: Symbol(react.element), ...}

有沒有辦法在 JSX/TSX 文件中使用{ withRedText(<HelloWorldComponent />) }之類的語法動態包裝組件?

(TypeScript 2.1.4 & React 15.4.0)

這是在 CodePen 上

那是因為在測試 #3 中,您向它傳遞了一個實例: <HelloWorldComponent /> ,而不是類型/類HelloWorldComponent JSX 被轉譯為大量對象實例化樣板。

我不認為您可以從 JSX 直接/隱式調用 HOC。 考慮 JSX 的實現以及 HOC 的工作方式,我認為這對性能沒有好處:每次組件重新渲染時,它都會再次調用 HOC 函數,重新創建包裝的組件類,然后調用它。

但是,您通常可以通過創建一個將另一個組件作為參數的組件來獲得類似的效果:

const WithRedText = ({component: Component, children, ...props}) => (
    <div style={{color: "red"}}>
      <Component {...props}>{children}</Component>
    </div>
);

(我以小寫形式傳遞component ,因為這似乎是 props 的約定,但在WithRedText ,我將其大寫,因為這是 JSX 識別自定義組件而不是 HTML 標簽的方式。)

然后,使用它:

ReactDOM.render(
    <div className="container">
        <WithRedText component={HelloWorldComponent} />
    </div>,
);

請參閱http://codepen.io/joshkel/pen/MJGLOQ

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM