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

问题描述 投票:0回答:1

我对各自的可重用 React 组件有 2 个问题。

  1. 我想要 React Component,它应该从 HTML 的

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

  2. 我还想在不复制

    ReactDOM.render
    的情况下重用 React 组件,而只是更改道具并根据类名安装组件。

[示例] 我将 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在这里!

javascript html jquery reactjs custom-data-attribute
1个回答
2
投票

像这样吗?

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)
}

小提琴:https://jsfiddle.net/rtLux0f6/1/

© www.soinside.com 2019 - 2024. All rights reserved.