【问题标题】:pass data in one function to another function inside a React component将一个函数中的数据传递给 React 组件中的另一个函数
【发布时间】: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


    【解决方案1】:

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

    <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'),
        )
    )
    
    

    【讨论】:

    • 问题是,{data} 只能在我的函数 ResearchTable() 中访问。所以我需要以某种方式将数据从 ResearchTable() 传递到 MyPortal()
    • 为什么不将所有这些都放在一个组件中,以便该组件内的所有内容都可以访问您的数据。您当前的return 可以是您组件的渲染函数,您也可以检索您在组件内部的函数中获取的数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2019-07-25
    • 2019-01-27
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多