【问题标题】:How to acess name attribute of iframe in React.js如何在 React.js 中访问 iframe 的名称属性
【发布时间】:2021-06-30 14:00:11
【问题描述】:

import React, { useState, useEffect } from 'react'
import "./MainText.css"
import "./App.css";
import FormatColorFillIcon from '@material-ui/icons/FormatColorFill';
import BorderColorIcon from '@material-ui/icons/BorderColor';

function MainText() {
    
    function enableEditMode() {
        textPart.document.designMode = 'On';
    }

    useEffect(() => {
        enableEditMode();
    }, [])

    return (
        <div className="mainText">

            <div className="mainText__second">
                <iframe name="textPart" frameBorder="0" ></iframe>
            </div>
        </div>
     )

我只显示了我没有得到结果的代码的主要部分。 我想访问 iframe 标记的 name 属性,但它显示 textPart 未定义。 我还尝试将 id 放入 iframe 并执行 document.getElementById 但它也不起作用。 帮帮我。

【问题讨论】:

    标签: javascript html reactjs iframe react-hooks


    【解决方案1】:

    您可以使用它来按名称获取元素: document.getElementsByName('textPart')

    所以在你的情况下 enableEditMode 代码将是:

      function enableEditMode() {
        const textpart = document.getElementsByName('textPart')[0];
        const iframeDocument= textpart.contentDocument || textpart.contentWindow.document;
        iframeDocument.designMode = "on";
      }
    

    【讨论】:

    • 它的意思是:不能设置未定义的属性'designMode'。
    • Iframe 组件没有文档属性。我更新了上面的代码,试试看。
    • 仍然无法正常工作。说“无法读取未定义的属性‘文档’”;
    • 我想我终于破解了。 getElementsByName() 返回一个数组,因此您需要获取第一个元素。因此,如果您尝试上面的代码,它应该可以工作。
    【解决方案2】:

    函数 MainText() {

        function enableEditMode(textPart) {
            if(!textPart){
            return;} // check for iframe content
            textPart.contentWindow.addEventListener("load", () => {
                   textPart.document.designMode = 'On'; // check content iframe when iframe loaded
            });
            
        }
    
        useEffect(() => {
            enableEditMode();
        }, [])
    
        return (
            <div className="mainText">
    
                <div className="mainText__second">
                    <iframe ref={this.enableEditMode} name="textPart" frameBorder="0" >/iframe>
                </div>
            </div>
         );
    

    您是否尝试过ref 更改 iframe 内容?

    【讨论】:

    • 在 iframe 中添加 ref 后。 "Cannot read property 'enableEditMode' of undefined" 这个错误来了。
    【解决方案3】:

    我觉得应该是这样的

    &lt;iframe name={"textPart"} frameBorder="0" &gt;&lt;/iframe&gt;

    【讨论】:

    • 不,还是说 textPart 没有定义。
    猜你喜欢
    • 2016-01-14
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多