在react.js上下文中获取html元素的数据属性 [英] Getting data attribute of html element in react.js context
问题描述
CMS将变量作为data-rest-url属性传递给React.js应用程序:
The CMS passes a variable as data-rest-url attribute to the React.js App:
<div id="reactjs-root" data-rest-url="http://my-ip-addess:8080/Rest-api-here">...</div>
如果我将jQuery添加到我的React.js应用程序中,那么我可以简单地说:
If I add jQuery to my React.js App, then I can simply:
componentWillMount() {
const $reactRoot = $('#reactjs-root');
const restUrl = $reactRoot.attr('data-rest-url');
}
但是为此添加jQuery?你如何将一些变量从CMS传递到单页反应应用程序并使用react.js读取/解析/获取它?
But adding jQuery just for this? How would you pass some variable from a CMS to your Single Page React App and read / parse / get it with react.js?
推荐答案
考虑将您的数据属性作为道具传递给组件,而不是在组件本身内对根元素ID进行硬编码。
Consider passing your data attributes to your component as props instead of hard coding the root element ID within the component itself.
渲染:
var rootElement = document.getElementById('reactjs-root');
ReactDOM.render(
<YourComponent resturl={rootElement.getAttribute('data-rest-url')}></YourComponent>,
rootElement
);
在组件中,您可以访问注入的网址:
Within the component you can access the injected url:
componentWillMount() {
console.log(this.props.resturl)
}
这使得一个更可重用的组件与特定的元素ID分离。
This makes for a more reusable component that is decoupled from a specific element ID.
这篇关于在react.js上下文中获取html元素的数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!