JSX 元素的 HOC - 使用包装元素渲染 jsx

我想调用 ReactJS HOC 来围绕 JSX 包装工具提示。

调用应该是这样的:


withTooltip(JSX, "very nice")

为此我创建了这个函数:


import React from "react";

import MUITooltip from "@material-ui/core/Tooltip";

import useStyles from "./index.styles";


const withTooltip = (Component, text: string) => (props) => {

  const classes = useStyles();

  return (

    <MUITooltip className={classes.root} title={text}>

      <Component {...props} />

    </MUITooltip>

  );

};

export default withTooltip;

电话:


import withTooltip from "commons/withTooltip/withTooltip";


  const dialogBtn =

    isOk &&

    withTooltip(

      <div className={classes.buttonWithLoader}>

        <OpenDialogButton

          variant={BaseButtonVariant.Icon}

          openDialogAttributes={areas.button.openDialogAttributes}

        />

      </div>,

      "Very nice",

    );

    

    

    return (

      <Fragment>

        {dialogBtn}

      </Fragment>

    );

它说:

函数作为 React 子项无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者也许你打算调用这个函数而不是返回它

如何解决?


幕布斯7119047
浏览 78回答 1
1回答

qq_遁去的一_1

Component当您传入 JSX 时,您的 HOC 接受一个参数。尝试用函数包装 JSX 或传入呈现按钮的组件。但是,在您的情况下,您可能希望控制组件中的工具提示文本。如果是这种情况,我不会为此使用 HOC,而是使用包装组件。function WithTooltip({ classes, text, children }) {&nbsp; return (&nbsp; &nbsp; <MUITooltip className={classes.root} title={text}>&nbsp; &nbsp; &nbsp; {children}&nbsp; &nbsp; </MUITooltip>&nbsp; );}export default WithTooltip;const dialogBtn = isOk && (&nbsp; <WithTooltip text="Very nice">&nbsp; &nbsp; <div className={classes.buttonWithLoader}>&nbsp; &nbsp; &nbsp; <OpenDialogButton&nbsp; &nbsp; &nbsp; &nbsp; variant={BaseButtonVariant.Icon}&nbsp; &nbsp; &nbsp; &nbsp; openDialogAttributes={areas.button.openDialogAttributes}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div>&nbsp; </WithTooltip>);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript