简体   繁体   English

当我将状态从 true 更改为 false 时,为什么我的模态不会隐藏在反应中?

[英]Why does my modal not hide in react when I change my state from true to false?

I have a modal component that is dependent on a state in a portfolio component that looks like this:我有一个模态组件,它依赖于投资组合组件中的状态,如下所示:

import React, { Component } from 'react';
import Modal from './Modal';
export default class Porfolio extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsOpen: false
    };
  }

  render() {
    const handleClose = () => {
      console.log("Is this working?")
      this.setState({ modalIsOpen: false })
    };
    let resumeData = this.props.resumeData;
    return (
      <section id="portfolio">
        <div className="row">
          <div className="twelve columns collapsed">
            <h1>Check Out Some of My Works.</h1>
            <div id="portfolio-wrapper" className="bgrid-quarters s-bgrid-thirds cf">
              {
                resumeData.portfolio && resumeData.portfolio.map((item) => {
                  return (
                    <div className="columns portfolio-item">
                      <div className="item-wrap">
                        <img src={`${item.imgurl}`} className="item-img" />
                        <div className="overlay" onClick={() => this.setState({ modalIsOpen: true })} >
                          {this.state.modalIsOpen ? <Modal item={item} handleClose={handleClose} /> : <div />}
                          <div className="portfolio-item-meta">
                            <h5>{item.name}</h5>
                            <p>{item.description}</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  )
                })
              }
            </div>
          </div>
        </div>
      </section>
    );
  }
}

My modal component is coded like this:我的模态组件是这样编码的:

import React, { Component } from 'react';
export default class Modal extends Component {
    render() {
        let item = this.props.item;
        let handleClose = this.props.handleClose;
        let state = this.props.state;
        return (

            <div className="popup-modal">
                <div className="modal-content">
                    <div className="description-box">
                        <button onClose={handleClose}>X</button>
                        <h4>Testing</h4>
                        <p>This is a test</p>
                        <a href="#">This is a clickable link</a>
                    </div>
                </div>
            </div >
        )
    }
}

My modal opens just fine when clicked, but on closing the test "x" button in my component, it seems to be running the function and I believe the state is being changed to false, but it is not hiding the modal.我的模态在单击时打开得很好,但是在我的组件中关闭测试“x”按钮时,它似乎正在运行该功能,我相信状态正在更改为 false,但它并没有隐藏模态。 Can anyone see if I'm missing anything?谁能看看我是否遗漏了什么?

For the full github repo: https://github.com/WarriorofZarona/React-Portfolio-1对于完整的 github 存储库: https : //github.com/WarriorofZarona/React-Portfolio-1

I believe your close click event is bubbling.我相信您的关闭点击事件正在冒泡。

Your code when rendered will be something like this:呈现时您的代码将是这样的:

<div className="overlay" onClick={() => this.setState({ modalIsOpen: true })} > // Click handler one
  this.state.modalIsOpen ? 
    <div className="popup-modal">
      <div className="modal-content">
        <div className="description-box">
          <button onClick={handleClose}>X</button> // Click handler two
          <h4>Testing</h4>
          <p>This is a test</p>
          <a href="#">This is a clickable link</a>
        </div>
      </div>
    </div >
 : <div />}
  <div className="portfolio-item-meta">
    <h5>{item.name}</h5>
    <p>{item.description}</p>
  </div>
</div>

The button onClick will always trigger the div onClick because the button is a child of the div . button onClick 将始终触发div onClick 因为该buttondiv的子项。 This means as soon as the modal is closed it will be re-opened.这意味着一旦模态关闭,它将重新打开。

To fix this, you need to call e.stopPropagation();要解决此问题,您需要调用e.stopPropagation(); from the inner click handler.从内部点击处理程序。

const handleClose = (e) => {
  e.stopPropagation();
  console.log("Is this working?")
  this.setState({ modalIsOpen: false })
};

Here are a few running examples to illustrate.这里有几个运行示例来说明。

Does not work:不起作用:

 class Example extends React.Component { constructor(props) { super(props); this.state = { open: false } } handleClick = (value) => { this.setState({ open: value }); } render() { console.log(this.state.open) return ( <div onClick={() => this.handleClick(false)}> <button onClick={() => this.handleClick(true)}>Click me</button> </div> ) } } ReactDOM.render(<Example/>,document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root" />

Does work:是否有效:

 class Example extends React.Component { constructor(props) { super(props); this.state = { open: false } } handleClick = (value) => { this.setState({ open: value }); } render() { console.log(this.state.open) return ( <div onClick={() => this.handleClick(false)}> <button onClick={(e) => { e.stopPropagation(); this.handleClick(true); }} >Click me</button> </div> ) } } ReactDOM.render(<Example/>,document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"/>

暂无
暂无

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

相关问题 为什么我的 div 仅在添加 isopen=true 属性时才动画,而在将值更改为 false 时却没有动画 - Why does my div only animate when i add an attribute of isopen=true but not when i change the value to false 当我在 React Native 中更新我的 State 时,我的 State 发生了变化,但组件消失了 如何解决这个问题? - My State Does Change But Components Are Disappear When I Update My State In React Native How To Fıx This? 在 React 应用程序中,我删除了 firebase 上的组件数据,但即使我更改了状态,它也不会从我的 dom 中删除 - In React app , I delete my component data on firebase but it does'n delete from my dom even when I change the state 为什么我的 `if(result !== &quot;false&quot;)` 返回 true? - Why does my `if(result !== "false")` return true? 为什么我的React孙子组件在收到其父组件的道具更改后没有更新? 或者:我需要使用状态吗? - Why does my React grandchild component not update after receiving a change in props from its parent? Or: do I need to use state? 从我的反应对象复制状态时,为什么我必须传播我的对象两次 - Why do I have to spread my object twice when copying state from my react object 为什么我的 if 语句在我手动更改选中状态时有效,但在单击按钮时无效 - Why does my if statement work if I manually change the checked state, but not when I click the button 为什么当 Set 状态改变时我的 React 组件没有重新渲染? - Why my React component does not rerender when Set state was changed? 反应:如果 1 state 为真,则将其他更改为假 - React: if 1 state is true, change others to false 当我在外面单击时,为什么我的js模式没有关闭? - Why does my js modal not close when I click outside?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM