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?您将如何将一些变量从 CMS 传递到您的单页 React 应用程序并使用 react.js 读取/解析/获取它?
最佳答案
考虑将数据属性作为 props 传递给组件,而不是在组件本身内对根元素 ID 进行硬编码。
渲染:
var rootElement = document.getElementById('reactjs-root');
ReactDOM.render(
<YourComponent resturl={rootElement.getAttribute('data-rest-url')}></YourComponent>,
rootElement
);
在组件中,您可以访问注入(inject)的 url:
componentWillMount() {
console.log(this.props.resturl)
}
这使得与特定元素 ID 分离的组件的可重用性更高。
关于javascript - 在 react.js 上下文中获取 html 元素的数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42783877/