【发布时间】: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 文件中父组件的 width 和 height 状态值?
【问题讨论】:
-
Render Props 也许?
标签: javascript reactjs react-hooks styled-components