簡體   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