首页 > 解决方案 > 通过不更新状态的道具将功能从父组件传递到子组件来关闭 react-bootstrap 弹出模式

问题描述

我无法this.togglePopup通过 props 将父函数传递给子组件来更新父反应组件的状态。

我可以通过将父组件传递给子组件来成功打开引导模式(react-bootstrap)this.state.open,但无法通过this.togglePopup传递给子组件的函数关闭弹出窗口/更新父组件的状态。

该应用程序是使用create-react-app.

公共/index.html

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <link
    rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
    crossOrigin="anonymous"
/>
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

src/App.js

import React from 'react';
import Parent from './components/Parent';
import './App.css';

function App() {
  return (
    <div className="App">
      <Parent></Parent>
    </div>
  );
}

export default App;

src/components/Parent.js

import React  from 'react';
import Child from './Child';

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false
        };
        this.togglePopup = this.togglePopup.bind(this);
    }

    togglePopup() {
        this.setState({
            open: !this.props.open
        });
    }

    render() {
        return (
            <div>
             <a onClick={this.togglePopup}>Open Modal</a>
                <Child show={this.state.open} parentAction={this.togglePopup}/>
            </div>
        );
    }
}

export default Parent;

src/components/Child.js(弹出模式)

import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';

class Child extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        show: props.show
      };
    }

    render() {
      return (
        <>
          <Modal show={this.props.show} onHide={this.props.parentAction}>
            <Modal.Header closeButton>
              <Modal.Title>Modal heading</Modal.Title>
            </Modal.Header>
            <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
            <Modal.Footer>
              <Button variant="secondary" onClick={this.props.parentAction}>
                Close
              </Button>
              <Button variant="primary" onClick={this.props.parentAction}>
                Save Changes
              </Button>
            </Modal.Footer>
          </Modal>
        </>
      );
    }
  }

export default Child;

当然,我错过了一些简单的事情。

非常感谢。

标签: reactjsreact-bootstrap

解决方案


togglePopup你使用道具的价值时,总是undefined. 你应该使用this.state.open

togglePopup() {
    this.setState({
        open: !this.state.open
    });
}

推荐阅读