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

nac*_*all 8 javascript jquery reactjs

CMS将变量作为data-rest-url属性传递给React.js应用程序:

<div id="reactjs-root" data-rest-url="http://my-ip-addess:8080/Rest-api-here">...</div>
Run Code Online (Sandbox Code Playgroud)

如果我将jQuery添加到我的React.js应用程序中,那么我可以简单地:

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

但是为此添加jQuery?你如何将一些变量从CMS传递到单页反应应用程序并使用react.js读取/解析/获取它?

MrC*_*ode 10

考虑将数据属性作为props传递给组件,而不是在组件本身内对根元素ID进行硬编码.

渲染:

var rootElement = document.getElementById('reactjs-root');
ReactDOM.render(
  <YourComponent resturl={rootElement.getAttribute('data-rest-url')}></YourComponent>,
  rootElement
);
Run Code Online (Sandbox Code Playgroud)

在组件中,您可以访问注入的URL:

componentWillMount() {
    console.log(this.props.resturl)
}
Run Code Online (Sandbox Code Playgroud)

这使得更可重用的组件与特定元素ID分离.


meh*_*mpt 5

const reactRoot = document.getElementById('reactjs-root');
const restUrl = reactRoot.getAttribute('data-rest-url');
Run Code Online (Sandbox Code Playgroud)

$另外,避免在变量名中使用。您可能会遇到许多与$您用作变量的库冲突的库。