如何使用 react-frame-component 添加点击事件并在 iframe 中获取 dom?

how add click event and get the dom in the iframe with react-frame-component?

我使用react-frame-component创建一个iframe,我想在iframe上绑定一个点击事件,并在iframe中获取id为abc的dom。怎么做到的?

上面是我的代码,它会输出null,得到的元素不是working.what 错了我的code.Help 会是appreciated.Thanks.

...
componentDidMount() {

    var iframe = document.getElementById("ccc");
    console.log(iframe);

    var iwindow = iframe.contentWindow;

    console.log(iwindow);

    var idoc = iwindow.document;

    console.log(idoc);

    console.log(idoc.getElementById('abc'));


  }
return (
      <div>
        <Frame id="ccc">
          <div id="abc">
            <div>this.state.show is true and now I'm visible</div>
          </div>
        </Frame>
      </div>
    );

像这样的东西可能有用...

import { FrameContextConsumer } from 'react-frame-component';

const MyComponent = (props) => {
    const frameWindow = useRef(null);

    const getInnerHTML = () => {
        const iframeWindow = frameWindow.current;
        if(!iframeWindow) return;

        // here you got the iframe window object
        // work with it as you like
    };

    return (
        <Iframe onClick={getInnerHTML}>
            <FrameContextConsumer>
                {(frameContext) => {
                    const { document, window } = frameContext;
                    frameWindow.current = window;

                    return <div>Your content goes in this return statement</div>
                }}
            </FrameContextConsumer>
        </Iframe>
    )
};

您需要使用 contentDidMount 道具(不是 componentDidMount)。

contentDidMount and contentDidUpdate are conceptually equivalent to componentDidMount and componentDidUpdate, respectively. The reason these are needed is because internally we call ReactDOM.render which starts a new set of lifecycle calls. This set of lifecycle calls are sometimes triggered after the lifecycle of the parent component, so these callbacks provide a hook to know when the frame contents are mounted and updated.

此代码应正确打印 console.log

export default class App extends Component {
  componentDidMount() {}

  contentMounted() {
    console.log("---------1");
    var iframe = document.getElementById("ccc");
    console.log("1", iframe);

    var iwindow = iframe.contentWindow;

    console.log("2", iwindow);

    var idoc = iwindow.document;

    console.log("3", idoc);

    console.log("4", idoc.getElementById("abc"));
  }

  render() {
    return (
      <div className="App">
        <Frame id="ccc" contentDidMount={this.contentMounted}>
          <div id="abc">
            <div>this.state.show is true and now I'm visible</div>
          </div>
        </Frame>
      </div>
    );
  }
}