【问题标题】:Passing React State Between Imported Components在导入的组件之间传递 React 状态
【发布时间】:2020-10-15 23:50:02
【问题描述】:

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

我有两个组件都从同一个文件中导出。第一个组件是第二个组件的包装器。这个组件有一个 useEffect 函数,它可以找到它的高度和宽度并将这些值设置为钩子状态。

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 状态值?

【问题讨论】:

标签: javascript reactjs react-hooks styled-components


【解决方案1】:

Render Props 可以工作:

renderTooltip 属性添加到&lt;TooltipWrapper&gt;

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

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

然后更新&lt;TooltipWrapper&gt;的返回:

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

【讨论】:

  • 我认为这是在正确的轨道上。我以前没有使用带有钩子的渲染道具。当我尝试此解决方案时,我在&lt;TooltipWrapper&gt; 上收到错误“TypeError: Cannot read property 'props' of undefined”
  • 你在...props 上还有其他道具,所以它只是props.renderTooltip();更新答案
  • 我认为如果我拔出...existing,这将起作用。我不确定那部分在做什么。
  • 那只是引用你现有的道具来省我把它们全部输入
猜你喜欢
  • 1970-01-01
  • 2019-07-24
  • 2017-10-24
  • 2020-05-16
  • 1970-01-01
  • 2022-10-12
  • 2018-08-10
  • 2021-07-06
  • 2018-06-06
相关资源
最近更新 更多