在 React 组件中检索自定义数据-* 属性值(无事件)

Retrieve custom data-* attributes value in React Component(without event)

我有 2 个关于可重用 React 组件的问题。

  1. 我想要 React Component,它应该从 HTML 的 data- 属性中获取 props 对象,这应该发生在加载而不是事件。 React 文档中显示的示例在 ReactDOM.render 方法中使用 props。我找不到从 data 属性中检索道具的示例。

  2. 我还想在不复制 ReactDOM.render 的情况下重用 React 组件,而只是更改道具并根据组件的 class 名称安装组件。

[示例] 我将 HTML 标记为,

<div class="blog" id="Politics" data-title="Political Science"></div>
<p>
Some description text..
</p>
<div class="blog" id="Economics" data-title="World Economy"></div>

React 组件是,

var propTitle = {
  'title': getTitle() //Function to retrieve data-title from respective component.
};
var Blog = React.createClass({
  render: function() {
    return (
      <h3>
        {this.props.blogtitle} 
      </h3>
    )
  }
}); 

ReactDOM.render(<Blog blogtitle={propTitle.title}/>,document.querySelectorAll('.blog'));

为了方便起见,JSFiddle来了!

是这样的吗?

var blogs = document.querySelectorAll('.blog');
for(var i = 0; i < blogs.length; i++){
    createComponent(blogs[i]);
}

function createComponent(blog){
    ReactDOM.render(<Blog blogtitle={blog.dataset.title} />, blog)
}

Fiddle: https://jsfiddle.net/rtLux0f6/1/