reactjs - 如何使用 ReactJS 嵌入 Gist

标签 reactjs gist

我尝试使用 ReactJS 嵌入 Gist,但出现以下错误:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

这是我的组件:

var EmbeddedGist = React.createClass({
    render: function() {
        return (
            <div id="gist-container" />
        );
    },

    componentDidMount: function() {
        var src = this.props.srcUrl + ".js";
        $('#gist-container').html('<script src="' + src + '"></script>');
    }
});

我从另一个组件中调用它,如下所示:

<EmbeddedGist srcUrl="https://gist.github.com/awalGarg/a5bd02978cecf3703f61" />

关于如何实现这项工作有什么想法吗?

最佳答案

Gist 嵌入脚本使用 document.write 将构成嵌入 Gist 的 HTML 写入到文档的 HTML 中。但是,当您的 React 组件添加 script 标记时,写入文档就为时已晚。

虽然您无法动态地将 Gist 嵌入脚本添加到页面中,但您可以通过 JSONP 获取 Gist 的内容并自行将其写入文档中。这是一个组件,它采用 gist 属性和可选的 file 属性并为您呈现要点。

var EmbeddedGist = React.createClass({
  propTypes: {
    gist: React.PropTypes.string.isRequired, // e.g. "username/id"
    file: React.PropTypes.string // to embed a single specific file from the gist
  },

  statics: {
    // Each time we request a Gist, we'll need to generate a new
    // global function name to serve as the JSONP callback.
    gistCallbackId: 0,
    nextGistCallback: function() {
      return "embed_gist_callback_" + EmbeddedGist.gistCallbackId++;
    },

    // The Gist JSON data includes a stylesheet to add to the page
    // to make it look correct. `addStylesheet` ensures we only add
    // the stylesheet one time.
    stylesheetAdded: false,
    addStylesheet: function(href) {
      if (!EmbeddedGist.stylesheetAdded) {
        EmbeddedGist.stylesheetAdded = true;
        var link = document.createElement('link');
        link.type = "text/css";
        link.rel = "stylesheet";
        link.href = href;

        document.head.appendChild(link);
      }
    }
  },

  getInitialState: function() {
    return {
      loading: true,
      src: ""
    };
  },

  componentDidMount: function() {
    // Create a JSONP callback that will set our state
    // with the data that comes back from the Gist site
    var gistCallback = EmbeddedGist.nextGistCallback();
    window[gistCallback] = function(gist) {
      if (this.isMounted()) {
        this.setState({
          loading: false,
          src: gist.div
        });
        EmbeddedGist.addStylesheet(gist.stylesheet);
      }
    }.bind(this);

    var url = "https://gist.github.com/" + this.props.gist + ".json?callback=" + gistCallback;
    if (this.props.file) {
      url += "&file=" + this.props.file;
    }

    // Add the JSONP script tag to the document.
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.head.appendChild(script);
  },

  render() {
    if (this.state.loading) {
      return <div>loading...</div>;
    } else {
      return <div dangerouslySetInnerHTML={{__html: this.state.src}} />;
    }
  }
});

你可以像这样使用它:

var app = (
  <div>
    <EmbeddedGist gist="BinaryMuse/a57ae1a551472e06b29a" file="restful.js" />
    <hr />
    <EmbeddedGist gist="BinaryMuse/bb9f2cbf692e6cfa4841" />
  </div>
);

React.render(app, document.getElementById("container"));

看看this example of it working on JSfiddle : http://jsfiddle.net/BinaryMuse/nrb6zxfw/

改进此问题的一种方法是确保具有 gistfile 属性更改的现有 EmbeddedGist 组件将更新以使用通过 Hook 到 componentWillReceiveProps 来获取新数据。

关于reactjs - 如何使用 ReactJS 嵌入 Gist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429361/

相关文章:

javascript - React Router v4 with Redux - dispatch 未通过

javascript - ReactJS - 在箭头函数中设置状态

javascript - React - 异步 api 调用,Promise.all 等待调用完成

javascript - 将数据从回调传递到 React 组件?

php - 如何在 markdown github gist 中使用 PHP 中的语法高亮显示?

github - 如何在 GitHub 中预览 Gist?

github - 要点修订限制?

github - 调试 gist-vim

python - 直接从 Jupyter 笔记本创建要点?

javascript - 如何帮助流程处理 react 组件状态初始化器?