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

Javascript 获取react.js上下文中html元素的数据属性,javascript,jquery,reactjs,Javascript,Jquery,Reactjs,CMS将变量作为数据rest url属性传递给React.js应用程序: <div id="reactjs-root" data-rest-url="http://my-ip-addess:8080/Rest-api-here">...</div> 但是仅仅为此添加jQuery?如何将CMS中的一些变量传递到单页React应用程序,并使用React.js读取/解析/获取它 const reactRoot = document.getElementById('reactj

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

<div id="reactjs-root" data-rest-url="http://my-ip-addess:8080/Rest-api-here">...</div>
但是仅仅为此添加jQuery?如何将CMS中的一些变量传递到单页React应用程序,并使用React.js读取/解析/获取它

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

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

考虑将数据属性作为道具传递给组件,而不是在组件本身中硬编码根元素ID

渲染:

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

这使得一个更可重用的组件与特定的元素ID解耦。

啊,这是一个更好的方法。好主意。你不需要jQuery。纯香草JavaScript很好用
document.getElementById('reactjs-root').dataset.restUrl
@Fred Sure,但它更难阅读,更容易出错(浏览器怪癖):通常,我更喜欢使用处理所有边缘情况的jQuery。使用React,您通常不需要jQuery,因此如果您只想从元素中获取属性,那么最好使用普通JavaScript来解决这个问题。您可以使用
dataset
属性,而不是
getAttribute
方法。
var rootElement = document.getElementById('reactjs-root');
ReactDOM.render(
  <YourComponent resturl={rootElement.getAttribute('data-rest-url')}></YourComponent>,
  rootElement
);
componentWillMount() {
    console.log(this.props.resturl)
}