【问题标题】:how add click event and get the dom in the iframe with react-frame-component?如何使用 react-frame-component 添加点击事件并获取 iframe 中的 dom?
【发布时间】:2020-05-28 13:17:26
【问题描述】:
我使用 react-frame-component 创建一个 iframe,我想在 iframe 上绑定一个点击事件并在 iframe 中获取 id 为 abc 的 dom。怎么做?
上面是我的代码,它会输出 null,让元素不起作用。我的代码有什么问题。感谢帮助。谢谢。
...
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>
);
【问题讨论】:
标签:
javascript
reactjs
iframe
react-component
【解决方案1】:
这样的事情可能会奏效......
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>
)
};
【解决方案2】:
你需要使用contentDidMount prop(不是componentDidMount)。
contentDidMount 和 contentDidUpdate 在概念上分别等同于 componentDidMount 和 componentDidUpdate。需要这些的原因是因为我们在内部调用 ReactDOM.render 来启动一组新的生命周期调用。这组生命周期调用有时会在父组件的生命周期之后触发,因此这些回调提供了一个挂钩来了解何时挂载和更新框架内容。
此代码应正确打印 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>
);
}
}