CMS将一个变量作为data-rest-url属性传递给React.js应用程序:
<div id="reactjs-root" data-rest-url="http://my-ip-addess:8080/Rest-api-here">...</div>
如果我将jQuery添加到我的React.js应用程序中,那么我可以简单地:
componentWillMount() {
const $reactRoot = $('#reactjs-root');
const restUrl = $reactRoot.attr('data-rest-url');
}
但是添加jQuery仅仅是为了这个吗?如何将一些变量从内容管理系统传递到您的单页面React应用程序,并使用react.js读取/解析/获取它?
发布于 2017-03-14 19:47:58
考虑将数据属性作为道具传递给组件,而不是在组件本身中硬编码根元素ID。
渲染:
var rootElement = document.getElementById('reactjs-root');
ReactDOM.render(
<YourComponent resturl={rootElement.getAttribute('data-rest-url')}></YourComponent>,
rootElement
);
在组件中,您可以访问注入的url:
componentWillMount() {
console.log(this.props.resturl)
}
这使得组件具有更高的可重用性,并且与特定的元素ID解耦。
发布于 2017-03-14 18:49:53
const reactRoot = document.getElementById('reactjs-root');
const restUrl = reactRoot.getAttribute('data-rest-url');
此外,请避免在变量名中使用$
。您可能会遇到许多库,这些库与您用作变量的$
冲突。
https://stackoverflow.com/questions/42783877
复制相似问题