使用Coral React和React和Meteor

Chr*_*r W 10 javascript mozilla meteor reactjs

我正在努力将Coral Talk项目评论系统应用到我的应用程序中.我试图将它实现到一个主要是Meteor和React的项目中.它在GitHub上

我认为主要问题是这是我第一次需要在React中使用脚本标记.
我试图通过componentDidMount中的dom,使用dangerouslySetHtml,尝试使用此建议,以及几个不同的包来加载脚本,但是在检查时只显示div和src,而不是页面本身的脚本内容.它的onload功能似乎没有被解雇.

通过设置另一个更简单的Node/Express应用程序,我已经确认了服务器并正确嵌入了代码功能.
这是我试图嵌入到我的React站点的代码:

<div id="coral_talk_stream"></div>
<script src="http://127.0.0.1:3000/static/embed.js" async onload="
  Coral.Talk.render(document.getElementById('coral_talk_stream'), {
    talk: 'http://127.0.0.1:3000/'
  });
"></script>
Run Code Online (Sandbox Code Playgroud)

任何建议将不胜感激.

Riv*_*Tam 4

我会完全在 React 之外完成此操作。所以把它放在你的main.html. 然后我会,而不是让 onload 只是

Coral.Talk.render(document.getElementById('coral_talk_stream'), {
  talk: 'http://127.0.0.1:3000/'
});
Run Code Online (Sandbox Code Playgroud)

将其更改为

window.renderCoralTo = function (id) {
  Coral.Talk.render(document.getElementById(id), {
    talk: 'http://127.0.0.1:3000/'
  });
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的组件中执行以下操作:

class CoralTalk extends Component {
  static divId = 'coral_talk_stream';

  shouldComponentUpdate() {
    return !this.rendered; // Stops the div from being remounted
                           // shouldn't be necessary, but a minor precaution
  }

  renderCoral = div => {
    if (!this.rendered && div != null) {
      window.renderCoralTo(CoralTalk.divId);
    }
  };

  render() {
    return (
      <div id={CoralTalk.divId} ref={this.renderCoral} />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我不是 100% 这会起作用,但看起来很可能会。

如果您只需要有时加载脚本标签(例如在某些页面上),您可以使用React HelmetPortals之类的东西来有条件地将脚本标签渲染到您的头部。

使用 Portals 的 100% 未经测试的示例:

class DynamicScript extends Component {
  render() {
    return React.createPortal(
      <script {...this.props} />,
      document.getElementsByTagName('head')[0]
    );
  }
}

class CoralTalk extends Component {
  static divId = 'coral_talk_stream';

  shouldComponentUpdate() {
    return !this.rendered; // Stops the div from being remounted
                           // shouldn't be necessary, but a minor precaution
  }

  render() {
    this.rendered = true;
    return (
      <Fragment>
        <ConditionalScript src="http://127.0.0.1:3000/static/embed.js" async onload={`
          Coral.Talk.render(document.getElementById('${CoralTalk.divId}'), {
            talk: 'http://127.0.0.1:3000/'
          });
        `} />
        <div id={CoralTalk.divId} />
      </Fragment>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)