您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

使用“ 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向下传递给子组件,并且当您想从子组件向上触发函数时,请在parent上创建一个回调函数

如果仍然无法解决问题,请随时向我显示一些错误日志,谢谢

其他 2022/1/1 18:13:35 有682人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶