簡體   English   中英

在 react.js 上下文中獲取 html 元素的數據屬性

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

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 讀取/解析/獲取它?

考慮將您的數據屬性作為道具傳遞給您的組件,而不是在組件本身內硬編碼根元素 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 分離。

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

另外,避免在變量名中使用$ 您可能會遇到許多與用作變量的$沖突的庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM