1

在熟悉 React 时,我偶然发现了开发人员文档中门户的概念。但是,我很难理解这个门户组件实际上是如何按需呈现的,以及我如何将数据传递给它以填充模式。

目前,我有两个相互交互的组件:View.jsDataTable.js.

View.js

const Example = (props) => {
    console.log(props);
    return (
        <div>
            <TopBar />
            <DeploymentsHeader env={props.match.params.env} />
            <PendingDataTable env={props.match.params.env} />
            <DataTable env={props.match.params.env} />
        </div>
    );
}

现在对于DataTable组件,正在呈现一个反应表。当用户单击单个行时,我的目标是弹出一个模式(我仍然不清楚如果我使用 React 门户,这是否需要有自己的单独组件)并填充数据已经绑定到单个行(我测试过并且也可以访问)。

代码看起来像这样:

<ReactTable
   data={tableData}
   filterable={true}
   getTrProps={this.onRowClick}
       columns={[
          {
            Header: "Header",
            accessor: "service_name"
           },
           ...
           ]}
/>

现在这是传递给表格行道具并在点击时执行的函数:

onRowClick = (state, rowInfo) => {
        return {
            onClick: e => {
                console.log('A Tr Element was clicked!');
                console.log(rowInfo.original);
            }
        }
    }

我需要的数据在对象中很容易获得rowInfo.original。现在我的问题是:当执行诸如此 onClick 触发器之类的事件时,使用门户加载模式的“正确”或“最佳实践”方式被认为是什么?

  1. 我是否需要有一个Modal.js实际上是门户的单独组件?
  2. 我如何从这个onRowClick函数中获取传输到这个模态门户的数据?

感谢大家。

4

2 回答 2

3

你可以有条件地渲染一个门户,就好像它只是另一个 React 组件一样。首先,您应该将模式分离到它自己的组件中。然后,您可以将项目 id 或项目存储在状态中并切换以让模式知道何时显示或不显示。

onRowClick = (state, rowInfo) => {
    return {
        onClick: e => {
            console.log('A Tr Element was clicked!');
            console.log(rowInfo.original);
            this.setState({
                data: rowInfo.original,
                showModal: true
            });
        }
    }
}

render() {
    return (
        <ReactTable
            data={tableData}
            filterable={true}
            getTrProps={this.onRowClick}
            columns={[
                {
                    Header: "Header",
                    accessor: "service_name"
                },
                ...
            ]}
        />
        {this.state.showModal &&  React.createPortal( <Modal data={this.state.data}>Your Data Goes Here</Modal>, document.getElementById('modal-portal')) }
    )
}

编辑:

他们的门户文档中有一个模态示例,您应该查看。

编辑2:

this.state.showModal是您需要添加的一个状态。您将使用它来有条件地渲染<Modal />组件(您创建的)。我在这里所做的是简写:

if(this.state.showModal) {
    return React.createPortal(...);
} else {
    return null;
}

至于实际的<Modal />组件,你可以随意制作,你可以使用react modal packagebootstrap modals或者只是构建你自己的。

示例自定义 Modal.js:

const Modal = ({ children, data }) => (
    <div className="my-modal">
        {children}
        // Here you can do stuff with data if you want
    </div>
);

CSS:

.my-modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
于 2017-10-16T20:11:43.140 回答
-1

注意 ReactDOM.createPortal 它的一个函数来自 react-dom 不反应

从“react-dom”导入 {createPortal}

于 2018-08-20T12:44:33.527 回答