简体   繁体   English

当我在 React 中按下按钮时,如何使它只出现一个特定的模式?

[英]How do I make it so only a specific modal appears when I press a button in React?

Currently trying to make modals in React and want to make a grid where "button 1" shows "modal 1" and "button 2" shows "modal 2" etc. At the moment when I press my button to show a modal it shows both modal 1 and modal 2. How do I set it up so button 1 only opens modal 1?目前正在尝试在 React 中制作模态,并希望制作一个网格,其中“按钮 1”显示“模态 1”,“按钮 2”显示“模态 2”等。当我按下按钮显示模态时,它同时显示modal 1 和 modal 2。如何设置按钮 1 只打开 modal 1?

This is my App.js:这是我的 App.js:

import React from 'react';
import './main.css';
import Modal from './components/Modal/modal';

class App extends React.Component {
  state = {
    show: false
  };

  showModal = x => {
    this.setState({
      show: !this.state.show
    });
  };

  render() {
    return (
      <div>
        <div className="button-container">
          <button className="toggle-button" onClick={x => {
            this.showModal(x);
          }}>Show yourself Modal!</button>
        </div>
        <Modal onClose={this.showModal} show={this.state.show} title="Test modal 1" id="1">Lorem ipsum</Modal>
        <Modal onClose={this.showModal} show={this.state.show} title="Test modal 2" id="2">I am a different modal</Modal>
      </div>
    );
  }
}

export default App;

And this is my modal.js component:这是我的 modal.js 组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './modal.css';

export default class Modal extends Component {
    onClose = x => {
        this.props.onClose && this.props.onClose(x);
    };

    render() {
        if(!this.props.show) {
            return null;
        }

        return (
            <div className="modal-wrapper">
                <h2 className="modal-header">{this.props.title}</h2>
                <div>{this.props.children}</div>
                <div>
                    <button className="modal-close" onClick={this.onClose}></button>
                </div>
            </div>
        )
    }
}

Modal.propTypes = {
    onClose: PropTypes.func.isRequired,
    show: PropTypes.bool.isRequired
};

The simplest way would be to add a second key to your state so that you have a way to manage showing both modals independently.最简单的方法是在 state 中添加第二个键,这样您就可以管理独立显示两个模态。

class App extends React.Component {
  state = {
    show1: false,
    show2: false
  };

Then make your change function to be a curried function that accepts a parameter to update the correct part of state.然后将 function 更改为接受参数以更新 state 的正确部分的咖喱 function。 In order to use a variable to access an object key, we need to access it as an array like this:为了使用变量来访问 object 键,我们需要像这样访问它作为数组:

  showModal = (modal) => (e) => {
    this.setState({
      [modal]: !this.state[modal]
    });
  };

Then use it like this:然后像这样使用它:

  render() {
    return (
      <div>
        <div className="button-container">
          <button className="toggle-button" onClick={this.showModal('show1')}>Show yourself Modal 1!</button>
          <button className="toggle-button" onClick={this.showModal('show2')}>Show yourself Modal 2!</button>
        </div>
        <Modal onClose={this.showModal('show1')} show={this.state.show1} title="Test modal 1" id="1">Lorem ipsum</Modal>
        <Modal onClose={this.showModal('show2')} show={this.state.show2} title="Test modal 2" id="2">I am a different modal</Modal>
      </div>
    );
  }
}

At the moment you have nothing in your state to tell which modal to show.目前,您的 state 中没有任何内容可以告诉您要显示哪个模态。 You're using this.state.show to control the visibility of both modals.您正在使用this.state.show来控制两种模式的可见性。

You could introduce a state property in your App component which is used to choose which modal to show.您可以在App组件中引入 state 属性,用于选择要显示的模式。 For example, passing in a modalId or similar to your click handler.例如,传入modalId或类似于您的点击处理程序。 ( disclaimer: untested syntax, but the principal is right!) 免责声明:未经测试的语法,但主体是正确的!)

So your state may look like this:因此,您的 state 可能如下所示:

state = {
  [
    { 
      id: 1,
      show: false
    },
    { 
      id: 2,
      show: false
    },
  ]
}

Then, in your click handler, you'd need to pass in the id of the modal to show / hide.然后,在您的点击处理程序中,您需要传入模态的 id 以显示/隐藏。 You'd need to determine this from something in your UI.您需要从 UI 中的某些内容中确定这一点。

showModal(id) => {
  this.setState({
    [id]: !this.state[id].show
  })
}

If you require Button for every Modal and control its behaviour with it then you can introduce a state to the modal component itself by doing something like this:如果您需要每个 Modal 的Button并使用它来控制其行为,那么您可以通过执行以下操作将 state 引入模态组件本身:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './modal.css';

export default class Modal extends Component {
    constructor(props) {
       super(props);
       this.state = {
         showModal: false,
       }
    }   

    toggleShow = () => {
        const { showModal } = this.state;
        this.setState({showModal: !showModal})
    };

    render() {
        const { showModal } = this.state;        
        return (
            <div className="modal-wrapper">
                { showModal &&
                <div>
                    <h2 className="modal-header">{this.props.title}</h2>
                    <div>{this.props.children}</div>
                </div>
                }
                <div>
                    <button className="modal-close" onClick={() => this.toggleShow()}>{this.props.btnText}</button>
                </div>
            </div>
        )
    }
}

It can be build further to alter the default behaviour.可以进一步构建它以更改默认行为。 This should clean your App.js code.这应该会清理您的App.js代码。

暂无
暂无

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

相关问题 当我从foreach列表中单击按钮时,如何激活它,仅激活该特定列表中的按钮? - how do I make it so when I click a button from a foreach list, it only activates the button in that specific list? 如何仅在用户按下 Enter 按钮时进行搜索? - How do I search only when user press enter button? 如何使出现其他功能时出现的按钮? - How do I make a button that appears when another function occurs? 我如何做到这一点,如果你按下一个按钮,然后再按下一个不同的按钮,你会在屏幕上看到一些东西? - How do i make it so that if you press a button and then a different button you will get something written on your screen? 我该怎么做才能让我在计算器应用程序中按下的每个按钮都将数字组合在一起? - How do I make it so each button I press in my calculator app combines the numbers together? 当我按下导航器上的按钮图标时如何应用,模式将使用本机反应自动弹出 - How to apply when I press the button icon on the navigator the modal will automatically popup using react native 如何使 window.prompt 变量仅在单击按钮时弹出? - How do I make so the window.prompt variables only pop up when a button is clicked? 单击禁用按钮时如何显示模式? - How do I make a modal appear when the disabled button is clicked? 按下按钮时如何只刷新特定的表? - How can I refresh only a specific table when I press a button? 如何在此JavaScript和HTML代码中添加按钮,以便在按下按钮时,交通信号灯序列运行一次? - How do i add a button to this JavaScript and HTML code so that when i press the button, my traffic light sequence runs once?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM