简体   繁体   English

在 react.js 上下文中获取 html 元素的数据属性

[英]Getting data attribute of html element in react.js context

The CMS passes a variable as data-rest-url attribute to the React.js App: CMS 将一个变量作为 data-rest-url 属性传递给 React.js 应用程序:

<div id="reactjs-root" data-rest-url="http://my-ip-addess:8080/Rest-api-here">...</div>

If I add jQuery to my React.js App, then I can simply:如果我将 jQuery 添加到我的 React.js 应用程序,那么我可以简单地:

 componentWillMount() {
    const $reactRoot = $('#reactjs-root');
    const restUrl = $reactRoot.attr('data-rest-url');
 }

But adding jQuery just for this?但是仅仅为此添加jQuery? How would you pass some variable from a CMS to your Single Page React App and read / parse / get it with react.js?您如何将一些变量从 CMS 传递到您的单页 React 应用程序并使用 react.js 读取/解析/获取它?

Consider passing your data attributes to your component as props instead of hard coding the root element ID within the component itself.考虑将您的数据属性作为道具传递给您的组件,而不是在组件本身内硬编码根元素 ID。

Rendering:渲染:

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:在组件中,您可以访问注入的 url:

componentWillMount() {
    console.log(this.props.resturl)
}

This makes for a more reusable component that is decoupled from a specific element ID.这使得更可重用的组件与特定元素 ID 分离。

const reactRoot = document.getElementById('reactjs-root');
const restUrl = reactRoot.getAttribute('data-rest-url');

Also, avoid using $ in your variable name.另外,避免在变量名中使用$ You're likely to run into a lot of libraries that conflict with the $ you have used as a variable.您可能会遇到许多与用作变量的$冲突的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM