【问题标题】:Retrieve custom data-* attributes value in React Component(without event)在 React 组件中检索自定义 data-* 属性值(无事件)
【发布时间】:2016-07-03 08:22:17
【问题描述】:

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

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

  2. 我还想在不复制 ReactDOM.render 的情况下重用 React 组件,而只需更改 props 并根据其类名安装组件。

[示例示例] 我的 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 jquery html reactjs html5-data


    【解决方案1】:

    这样的?

    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/

    【讨论】:

    • 太棒了!这就是我一直在寻找的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 2014-01-06
    • 2011-04-24
    相关资源
    最近更新 更多