草庐IT

javascript - React Modal 不会在加载内容之间关闭

coder 2024-07-15 原文

我正在使用这个 React 模态插件:https://github.com/reactjs/react-modal 我需要在页面加载时在模态中显示一组对象。当第一个项目显示用户单击按钮时,isOpen 属性将 Modal 设置为 false。每个项目都有一个 showModal 属性,它将值提供给 Modal 的 isOpen。随着用户不断单击,我不断将当前对象的值设置为 false,然后为下一个对象将其设置为 true。 这一切都很好,但问题是覆盖和对话窗口停留在屏幕上,只有模态内的内容被更新。我希望模式完全关闭并打开以显示数组中下一个对象的内容。我不得不将我的代码剥离为以下简化版本:

class ProductsModal extends React.Component {
  constructor(props) {
    super(props);
    this.remindMeHandler = this.remindMeHandler.bind(this);

    this.state = {
      products: [],
      modalId: 0
    };
  }

showModals() {
    let products = this.state.products;
    //A different function saves the array of product objects in the state so 
    //I can show them one by one

    let currentProduct = products[this.state.popUpId];

    if (products.length > 0) {
      return <ProductItemModal 
              product={currentProduct}
              showNextPopUp={() => this.showNextPopUp(currentProduct.productId)}
              showPopUp={currentProduct['showModal']}
              />;
    //showModal is a boolean for each product that sets the value of isOpen
    }
  }

  showNextPopUp() {
      //All this does is sets the "showModal" property to false for current 
     //product and sets it to true for next product so it shows in the Modal
  }


render() {
    return(
      <div>
        {this.showModals()}
      </div>
    );
  }
}

class ProductItemModal extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(
      <Modal 
        isOpen={this.props.showModal}
        contentLabel="Product"
        id={this.props.product.productId}
        >
        <div>
         Product Data......
        </div>
      </Modal>
    );
  }
}

最佳答案

有解决所有问题的方法并创建了这个 codepen link .会是这样的,

class ProductItemModal extends React.Component {
  render() {
    const { showModal, product, showNextModal, onClose } = this.props;

    return(
      <ReactModal 
        isOpen={showModal}
        contentLabel="Product"
        onRequestClose={() => onClose()}
        >
        <p>
          <b>Product Id</b> - {product.id}, <b>Product Name</b> - {product.name}
        </p>
        <button onClick={() => showNextModal()}>Next</button>
      </ReactModal>
    );
  }
}

class ProductsModal extends React.Component {
  constructor() {
    super();

    this.state = {
      products: [
        {id: 1, name: "Mac", showModal: true},
        {id: 2, name: "iPhone", showModal: false},
        {id: 3, name: "iPod", showModal: false},
      ],
      modalId: 0
    };
  }

  handleProductItemModalClose(product) {
    //backdrop click or escape click handling here
    console.log(`Modal closing from Product - ${product.name}`);
  }

  showModals() {
    const { products, modalId } = this.state;
    //A different function saves the array of product objects in the state so 
    //I can show them one by one

    let currentProduct = products[modalId];

    if(currentProduct) {
      return <ProductItemModal 
              product={currentProduct}
              showNextModal={() => this.showNextModal(currentProduct.id)}
              showModal={currentProduct["showModal"]}
              onClose={() => this.handleProductItemModalClose(currentProduct)}
              />;
    //showModal is a boolean for each product that sets the value of isOpen
    }
  }

  showNextModal(currentProductId) {
    const { products, modalId } = this.state;

    var isLastModal = false;
    if(modalId === products.length - 1) {
      isLastModal = true;
    }

    var clonedProducts = [...products];
    var currentIndex = clonedProducts.findIndex(product => product.id === currentProductId);
    var newIndex = currentIndex + 1;
    clonedProducts[currentIndex].showModal = false;
    if(!isLastModal) {
      clonedProducts[newIndex].showModal = true;
    } else {
      //comment the following lines if you don't wanna show modal again from the start
      newIndex = 0;
      clonedProducts[0].showModal = true;
    }
      //All this does is sets the "showModal" property to false for current 
     //product and sets it to true for next product so it shows in the Modal
    this.setState({
      products: clonedProducts
    }, () => {
      this.setState({
        modalId: newIndex
      });
    });
  }

  render() {
    return(
      <div>
        {this.showModals()}
      </div>
    );
  }
}

ReactDOM.render(<ProductsModal />, document.getElementById("main"));

如果有帮助,请告诉我。

更新代码笔:https://codepen.io/anon/pen/rzVQrw?editors=0110

关于javascript - React Modal 不会在加载内容之间关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228757/

有关javascript - React Modal 不会在加载内容之间关闭的更多相关文章

  1. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  2. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  3. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  4. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  5. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  6. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  7. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  8. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  9. ruby-on-rails - `a ||= b` 和 `a = b if a.nil 之间的区别? - 2

    我正在检查一个Rails项目。在ERubyHTML模板页面上,我看到了这样几行:我不明白为什么不这样写:在这种情况下,||=和ifnil?有什么区别? 最佳答案 在这种特殊情况下没有区别,但可能是出于习惯。每当我看到nil?被使用时,它几乎总是使用不当。在Ruby中,很少有东西在逻辑上是假的,只有文字false和nil是。这意味着像if(!x.nil?)这样的代码几乎总是更好地表示为if(x)除非期望x可能是文字false。我会将其切换为||=false,因为它具有相同的结果,但这在很大程度上取决于偏好。唯一的缺点是赋值会在每次运行

  10. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

随机推荐