在 React 组件中从外部加载的 HTML 访问内部函数

IT技术 reactjs
2021-05-06 15:54:56

我有以下用例。

来自第三方源的一些 HTML 加载到我的 React 组件中:

class MyComponent extends Component {
  render() {
    return (
      <div
        dangerouslySetInnerHTML={{ __html: this.props.externalHTML }}
      />
    );
  }
}

在外部加载的 HTML 中,存在针对特定跨度的单击事件,该事件应该调用我的应用程序中存在的回调函数。

<span onclick="myCallback(param1='asd', param2=123, param3='asdas')">
  Click me!
</span>

我应该把这个myCallback函数放在哪里

如果我将它放在组件类中,单击跨度时会出现以下错误,因为据我所知,该函数对外部加载的 HTML 不可见:Uncaught ReferenceError: myCallback is not defined at HTMLSpanElement.onclick

我的另一个想法是将函数添加到window.myCallback = ...我的主 index.js 文件中的 window 对象,以便在每次应用加载时加载。这种方式有效,但我有两个问题。

  • 我的理解是,这不是正确的 React 方式。
  • 每当我单击 span 元素时,回调函数都会触发两次,我不明白为什么。

有什么建议?

1个回答

使用 "dangerouslySetInnerHTML" 是......"dangerous" 作为它的名字 ^^,这实际上也不是纯粹的 React 方式。

但是,如果你必须这样做,你可以做这样的事情(利用 React 内置的 jQuery 是默认的)

======

来自此处的编辑版本:(仅使用 1 个组件)

export default class MyComponent extends Component {
  componentDidMount() {
    // using jQuery to manipulate DOM element form third-party source
    // NB. you may think of using setTimeout here, to wait for the external source to be fully loaded here, of course it's not so safe
    // but anyway, we are using "dangerouslySetInnerHTML" anyway => quite dangerous, though ^^  

    // setTimeout(function(){   
      $(document.findElementsByTagName("span")[0]).click(function(e){ 
      // or perhaps $("#spanID").click if you can, just be careful between DOM element and react component

          e.preventDefault();
          // DO SOMETHING HERE, just like you do in the window.onload function
          // or maybe you also need to get param values by getting $(this).data("...") or $(this).attr("ATTRIBUTE-NAME")
          return false;

      });
    // });
  }
  render() {
    return (
      <div
        dangerouslySetInnerHTML={{ __html: this.props.externalHTML }}
      />
    );
  }
}   

======

来自这里的旧答案:(使用 2 个组件)

父组件:

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.callbackOnThisComponent = this.callbackOnThisComponent.bind(this);
  }
  callbackOnThisComponent(param1, param2, param3) {
    // do whatever you like with the above params
  }
  render() {
    return (
      <ChildComponent triggerCallbackOnParent={this.callbackOnThisComponent} />
    );
  }
}

子组件:

export default class ChildComponent extends Component {
  componentDidMount() {
    // using jQuery to manipulate DOM element form third-party source

    let that = this;

    // NB. you may think of using setTimeout here, to wait for the external source to be fully loaded here, of course it's not so safe
    // but anyway, we are using "dangerouslySetInnerHTML" anyway => quite dangerous, though ^^  

    $(document.findElementsByTagName("span")[0]).click(function(e){ 
    // or perhaps $("#spanID").click if you can, just be careful between DOM element and react component

        e.preventDefault();
        that.props.triggerCallbackOnParent(param1, param2, param3);
        // or maybe you need to get param values by getting $(this).data("...") or $(this).attr("ATTRIBUTE-NAME")
        return false;

    }, that);

  }
  render() {
    return (
      <div
        dangerouslySetInnerHTML={{ __html: this.props.externalHTML }}
      />
    );
  }
}   

我只是使用React的主要思路,将props向下传递给子组件,当你想从子组件向上触发一个函数时,在父组件上创建一个回调函数。供您或任何其他人参考,这是我关于如何将回调函数从父组件传递到多级子组件的演示:

强制 React 容器刷新数据

重定向时重新初始化类

如果这还不起作用,请随时向我展示一些错误日志,谢谢