如何解决在 ReactJS 中读取和更新 Iframe src 字段
我想嵌入一个网站,该网站在通过 IFrame 元素与 React 应用程序交互时更改其 URL 查询参数。我想从我的父窗口/React 组件中检索和更新此查询参数,但我无法获得正确的引用。
我试图查看 into different libraries,但这些都没有帮助我解决这个问题。我还尝试使用 useRef
获取对 iframe 的引用,并访问 src
参数,但在交互后没有改变。
下面的代码片段解释了这个问题:
import React,{ useState,useRef } from "react"
const MyComponent = () => {
// URL of the following form,the site changes "position" based on
// interaction and change events,which I want to read/update
const url = 'https://example.com/#!{"position": 123}'
const [myUrl,setMyUrl] = React.useState(url)
const child1 = useRef(null);
const showData = () => {
// the following target src is always the
// initial src,not the updated src after interation
console.log(child1.current.src)
}
const setData = () => {
// setting only the query parameter of the url
// setMyUrl(...)
}
return (
<div>
<button type="button" onClick={showData}>Show data</button>
<button type="button" onClick={setData}>Set Url</button>
<iframe src={myUrl} width="100%" height="300" ref={child1} />
</div>
)
}
export default MyComponent;
感谢您的帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。