gpt4 book ai didi

javascript - 将一个函数中的数据传递给 React 组件内的另一个函数

转载 作者:行者123 更新时间:2023-12-02 21:07:23 25 4
gpt4 key购买 nike

我有一个 React 组件,它返回一个包含数据的表。

我还使用 React Portal 在表格顶部打开一个新的 Div。

我想将表中的数据传递到 React Portal。

在下面的代码中,您可以看到门户名为 MyPortal,表名为 ResearchTable。

表中显示的数据称为“data”,在本例中,我在表中显示“data.astronomyTitle”。

我还想在弹出的 React Portal 中显示“data.astronomyTitle”。

但我不知道如何访问代码的 MyPortal 部分中的“数据”,因为“数据”仅位于表部分中。

所以我的问题是,有什么方法可以将数据传递到MyPortal吗?或者也许将其保存在一个全局变量中,然后可由 MyPortal 访问?

谢谢!

const MyPortal = ({ children }) => (

ReactDOM.createPortal(
<div id="portal_GalaxyDetails">
{children}
</div>,
document.getElementById('portal-root'),
)
)

function ResearchTable() {
const [isShown, setIsShown] = React.useState(false);
const hide = () => setIsShown(false);
const show = () => setIsShown(true);

{
Header: 'Research Opportunities',
columns: [
{
id: <td>{data.astroId}</td>
},

{
title: <td><a href="#" onClick={show}>{data.astronomyTitle}</a></td>
}
]

const [data, setData] = React.useState([]);
React.useEffect(() => {
galaxyData().then(res => {
setData(res.data);
});
}, []);

return (
<div id="mainContent">
<table>
<tr>
{columns}
</tr>
</table>
</div>

{isShown && (
<MyPortal>
<p>This is my portal</p>
<button onClick={hide}>Close</button>
</MyPortal>
)}
);

最佳答案

将数据作为 Prop 发送到门户,即

<MyPortal astroId={data.astroId}>
<p>This is my portal</p>
<button onClick={hide}>Close</button>
</MyPortal>

然后确保您在 Portal 组件中拾取 Prop :

const MyPortal = ({ astroId, children }) => (

ReactDOM.createPortal(
<div id="portal_GalaxyDetails">
<p>{astroId}</p>
{children}
</div>,
document.getElementById('portal-root'),
)
)

关于javascript - 将一个函数中的数据传递给 React 组件内的另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61191969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com