简体   繁体   English

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

[英]HOC for JSX element - rendering jsx with wrapped element

I want to call a ReactJS HOC to wrap a tooltip around JSX.我想调用一个 ReactJS HOC 来围绕 JSX 包装一个工具提示。

The call should be able like this:调用应该是这样的:

 withTooltip(JSX, "very nice")

Therefor I have created this function:因此我创建了这个函数:

 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;

The call:电话:

 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> );

It says:它说:

Functions are not valid as a React child.函数作为 React 子元素无效。 This may happen if you return a Component instead of from render.如果您返回 Component 而不是从 render 返回,则可能会发生这种情况。 Or maybe you meant to call this function rather than return it或者也许你打算调用这个函数而不是返回它

How to solve it ?如何解决?

Your HOC accepts a Component argument while you are passing in JSX.当您传入 JSX 时,您的 HOC 接受一个Component参数。 Try wrapping the JSX with a function or pass in a component which renders the Button.尝试使用函数包装 JSX 或传入呈现按钮的组件。

However, in your case, you probably want to have control over the toolTip text in your component.但是,在您的情况下,您可能希望控制组件中的工具提示文本。 If this is the case, I would not use a HOC for this, but rather a wrapping Component.如果是这种情况,我不会为此使用 HOC,而是使用包装组件。

function WithTooltip({ classes, text, children }) {
  return (
    <MUITooltip className={classes.root} title={text}>
      {children}
    </MUITooltip>
  );
}

export default WithTooltip;
const dialogBtn = isOk && (
  <WithTooltip text="Very nice">
    <div className={classes.buttonWithLoader}>
      <OpenDialogButton
        variant={BaseButtonVariant.Icon}
        openDialogAttributes={areas.button.openDialogAttributes}
      />
    </div>
  </WithTooltip>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM