简体   繁体   English

在React中重用模态

[英]reuse Modals in React

I have a very simple modal that I want to reuse to display dynamic data 我有一个非常简单的模式,我想重用它来显示动态数据

class Modal extends Component {

    constructor(props) {
        super(props)
        this.handleKeyDown = this.handleKeyDown.bind(this);
        this.handleCloseModal = this.handleCloseModal.bind(this);
    }

    handleKeyDown(event) {
        if (event.key === 'Escape') {
            this.handleCloseModal()
        }
    }

    handleCloseModal() {
        // What should I do here? Unmount?
    }

    componentDidMount() {
        document.addEventListener('keydown', this.handleKeyDown, false);
    }

    render() {

        return(

            <div className="modal">
                <button onClick={() => this.handleCloseModal()}>close modal</button>
                {this.props.children}
            </div>

        )
    }
}

export default Modal

I would like to open the modal with the data from elem.description for each elem in the records array. 我想用记录数组中每个elem的 elem.description数据打开模态。

{records.map(function(elem, index) {
    return <button 
            key={index} 
            onClick={// Something like <Modal>{elem.description}</Modal>} 
        /> open modal for {elem.name}</button>
})}

I read about some implementations that will do something like 我读到了一些类似的实现

<Modal show=true>...</modal>

and toggle the visibility of it. 并切换它的可见性。 can i Just Unmount the component? 我可以卸载组件吗? is that aa good practice? 这是一个好习惯吗?

One way of doing that is to save the clicked element in the state and then, when it is clicked display the modal. 一种方法是将点击的元素保存在状态中,然后在单击时显示模态。

{records.map(function(item, index) {
    return <button 
            key={index} 
            onClick={this.openModal(item)} // open modal and set the current item in the state
        /> open modal for {elem.name}</button>
})}

You need a function to set the element as current and open the modal 您需要一个函数将元素设置为当前并打开模态

openModal = (item) =>() => {
 this.setState({currentItem:item, isModalVisible: true})
}

Finally in your modal just pass an item component as chidlren and give it data coming from the state 最后在你的模态中,只需将一个项目组件作为chidlren传递,并为其提供来自状态的数据

<Modal isVisible={this.state.isModalVisible}>
  <MyItem data={this.state.currentItem} />
</Modal>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM