首页 > 解决方案 > 如何使用 React/Next.js 将数据传递到模态?

问题描述

我有一个表,当用户单击表中的一行时,我想在模态图中显示行数据。然后,用户将能够编辑此数据,然后将其更新到服务器。

我正在使用 Next.js 构建网站,并且尝试了许多不同的 React 解决方案,但似乎没有一个有效。我正在寻找一个可靠、简单的解决方案。

标签: reactjsmodal-dialog

解决方案


我建议在这种情况下使用可重用的模态组件,我在我的项目中这样做。

这将是一个完全可重用的组件,它将包裹在您传入的任何内容上并将其转换为模态。

React非常强大,我们只需要知道如何使用它!

模态组件

import React, { Component } from 'react';

import classes from './Modal.css';
import Aux from '../../../hoc/Auxiliary/Auxiliary';
import Backdrop from '../Backdrop/Backdrop';

class Modal extends Component {

    shouldComponentUpdate ( nextProps, nextState ) {
        return nextProps.show !== this.props.show || nextProps.children !== this.props.children;
    }

    render () {
        return (
            <Aux>
                <Backdrop show={this.props.show} clicked={this.props.modalClosed} />
                <div
                    className={classes.Modal}
                    style={{
                        transform: this.props.show ? 'translateY(0)' : 'translateY(-100vh)',
                        opacity: this.props.show ? '1' : '0'
                    }}>
                    {this.props.children}
                </div>
            </Aux>
        )
    }
}

export default Modal;

背景组件

import React from 'react';

import classes from './Backdrop.css';

const backdrop = (props) => (
    props.show ? <div className={classes.Backdrop} onClick={props.clicked}></div> : null
);

export default backdrop;

好吧,不要对辅助感到困惑,它只是一个HOC,可以避免添加额外的包装 div

辅助 HOC

const Aux = (props) => props.children;

export default Aux; 

推荐阅读