在ReactJS中动态onClick和渲染

时间:2015-08-14 08:09:38

标签: javascript html reactjs

我是React的新手,我需要一些帮助来解决这个问题!

我有一个Json对象:

var exampleJson = {
    title: "title",
    blocks: [
        {
            type: "block1",
            items: [{id: "1", count: 1},
                    {id: "2", count: 1},]
        },
        {
            type: "block2",
            items: [{id: "3", count: 1},
                    {id: "4", count: 1},]
        },
]};

我想获取对象中的每个块并在div中呈现每个块内的数据(包括循环遍历块内的项)。 div应该有一个动态onClick事件,用于注册单击块。

这就是我得到的:

var BlockListClass = React.createClass({
blockClicked: function() {
    // Here I dont know what block I clicked
},
loopBlocks: function(_data, blockClicked) {
         // loop blocks
        {_data.map(function(object, i){
            var result = <div className="block" key={i}> 
                      {[ 
                         <h2 onClick={blockClicked} key={i}> {object.type} </h2>
                      ]}
                  </div>; 
         // Loop items
         for (var key in object.items) {
              if (object.items.hasOwnProperty(key)) {
               result.props.children.push(<h2 key={key+10}> {object.items[key].id} </h2>);
              }
            }
         return result;
         })}
},
render: function() {
  var _data = exampleJson.blocks;
  var blockClicked = this.blockClicked;
  var renderer = this.loopBlocks(_data,blockClicked);
  return(
    <div className="BlockList">
    {renderer}
    </div>
    );
}

});

然后像这样呈现BlockListClass:

<BlockListClass />

1 个答案:

答案 0 :(得分:0)

//你可以做这样的事情

var BlockListClass = React.createClass({
blockClicked: function(e) {
    var id = e.currentTarget.id;
    console.log(id);
},
loopBlocks: function(_data, blockClicked) {
         // loop blocks
        {_data.map(function(object, i){
            var result = <div className="block" key={i}> 
                      {[ 
                         <h2 onClick={blockClicked} id={i} key={i}> {object.type} </h2>
                      ]}
                  </div>; 
         // Loop items
         for (var key in object.items) {
              if (object.items.hasOwnProperty(key)) {
               result.props.children.push(<h2 key={key+10}> {object.items[key].id} </h2>);
              }
            }
         return result;
         })}
},
render: function() {
  var _data = exampleJson.blocks;
  var blockClicked = this.blockClicked;
  var renderer = this.loopBlocks(_data,blockClicked);
  return(
    <div className="BlockList">
    {renderer}
    </div>
    );
}
});