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

问题描述 投票:0回答:1

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

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

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

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

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

我也想在弹出的React Portal中显示'data.astronomyTitle'。

但是我无法在代码的MyPortal部分中弄清楚如何访问'data',因为'data'仅在Table部分。

所以我的问题是,有什么方法可以将数据传递给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
1个回答
0
投票

即作为道具将数据发送到门户。

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

然后确保您要在Portal组件中拾取道具:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.