繁体   English   中英

在导入组件之间传递 React State

[英]Passing React State Between Imported Components

我正在尝试使用 React 将 state 从父级传递给子级,但是这两个组件都是导入的,因此未声明父组件的 state 变量。

我有两个组件都从同一个文件中导出。 第一个组件是第二个组件的包装器。 这个组件有一个 useEffect function 找到它的高度和宽度并将这些值设置为挂钩 state。

export const TooltipWrapper = ({ children, ariaLabel, ...props }) => {
  const [width, setWidth] = React.useState(0);
  const [height, setHeight] = React.useState(0);
  const ref = React.useRef(null);
     React.useEffect(() => {
       if (ref.current && ref.current.getBoundingClientRect().width) {
         setWidth(ref.current.getBoundingClientRect().width);
       }
       if (ref.current && ref.current.getBoundingClientRect().height) {
         setHeight(ref.current.getBoundingClientRect().height);
       }
     });
  return <TooltipDiv>{children}</TooltipDiv>;

从同一文件导出的下一个组件如下所示

export const Tooltip = ({
  ariaLabel,
  icon,
  iconDescription,
  text,
  modifiers,
  wrapperWidth,
}) => {
  return (
    <TooltipContainer
      aria-label={ariaLabel}
      width={wrapperWidth}
    >
      <TooltipArrow data-testid="tooltip-arrow" modifiers={modifiers} />
      <TooltipLabel
        aria-label={ariaLabel}
      >
        {text}
      </TooltipLabel>
    </TooltipContainer>
  );
};

组件Tooltip需要一个道具wrapperWidth 这是我想从TooltipWrapper组件传递宽度挂钩值的地方。

两个组件都导入到我的 App 组件中

import React from "react";
import { GlobalStyle } from "./pattern-library/utils";
import { Tooltip, TooltipWrapper } from "./pattern-library/components/";


function App() {
  return (
    <div className="App">
      <div style={{ padding: "2rem", position: "relative" }}>
        <TooltipWrapper>
          <button style={{ position: "relative" }}>click </button>
          <Tooltip
            modifiers={["right"]}
            text="changing width"
            wrapperWidth={width}
          />
        </TooltipWrapper>
      </div>
    </div>
  );
}

在这里,我被告知未定义宽度,这是我所期望的,因为我没有在此文件中声明宽度。

有谁知道我如何访问 App 文件中父组件的widthheight state 值?

渲染道具可以工作:

renderTooltip添加到<TooltipWrapper>

<TooltipWrapper renderTooltip={({ width }) => <Tooltip ...existing wrapperWidth={width} />}>
  <button style={{ position: 'relative' }}>click</button>
</TooltipWrapper>

注意。 ...existing只是您与Tooltip一起使用的其他道具

然后更新<TooltipWrapper>的返回:

return (
  <TooltipDiv>
    {children}
    props.renderTooltip({ width }); 
  </TooltipDiv>
);

暂无
暂无

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

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