微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 ReactJS 中读取和更新 Iframe src 字段

如何解决在 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?