【发布时间】:2020-04-13 16:10:22
【问题描述】:
我有一个 React 组件,它返回一个包含数据的表格。
我还使用 React Portal 在表格顶部打开一个新的 Div。
我想将表中的数据传递到 React Portal。
在下面的代码中,您可以看到门户名为 MyPortal,表名为 ResearchTable。
表中显示的数据称为“数据”,在此示例中,我在表中显示“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>
)}
);
【问题讨论】:
标签: javascript reactjs react-table