父组件监听子组件iframe内部点击事件并做出相应

432 阅读1分钟

要实现的效果:

  1. 点击按钮展示一个弹窗
  2. 弹窗内嵌套一个iframe
  3. ifame做出点击某个按钮的时候,关闭弹窗

物料

  1. 参考链接
  2. api

代码实现

import React from "react";
import { Modal, Button } from "antd";

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

  showModal = () => {
    this.setState({ visible: true });
  };

  handleCancel = () => {
    this.setState({ visible: false });
  };

  receiveMessage = (event) => {
    const { origin, data } = event || {};
    if (origin !== "https://juejin.cn/") {
      return;
    }
    if (data === "closeModal") {
      this.handleCancel();
    }
  };

  render() {
    window.addEventListener("message", this.receiveMessage, false);

    return (
      <>
        <Button onClick={this.showModal}>查看</Button>
        <Modal
          width="800"
          height="600"
          visible={this.state.visible}
          title="抽屉"
          onCancel={this.handleCancel}
          footer={null}
        >
          <iframe
            height="600"
            width="100%"
            src={"https://juejin.cn/"}
            id="childIframe"
            title="navigation"
            X-Frame-Options="ALLOWALL"
          />
        </Modal>
      </>
    );
  }
}

export default App;