Gist 嵌入脚本使用document.write
将构成嵌入 Gist 的 HTML 写入文档的 HTML 中。然而,当你的 React 组件添加script
标签,现在写入文档为时已晚。
虽然您无法将 Gist 嵌入脚本动态添加到您的页面,但您can得到contents通过 JSONP 获取要点并自己将其写入文档中。这是一个需要一个组件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"));
看一眼这个例子是在 JSfiddle 上运行的 http://jsfiddle.net/BinaryMuse/nrb6zxfw/: http://jsfiddle.net/BinaryMuse/nrb6zxfw/ http://jsfiddle.net/BinaryMuse/nrb6zxfw/
改进这一点的一种方法是确保现有的EmbeddedGist
具有其gist
or file
道具更改将通过挂钩更新以使用新数据componentWillReceiveProps
.