2014-11-23 78 views
3

我开始学习React,并且我撞到了第一面墙。React,在组件中添加组件

我有一个列表组件,它应该显示一个行+列表添加一个新行的列表。

所有在那些2个学家:在点击执行

https://gist.github.com/matiit/7b361dee3f878502e10a

https://gist.github.com/matiit/8bac28c4d5c6ce3993c7

的addRow方法,因为我能看到的console.log,但没有添加InputRows。

真的不明白为什么。

这是一个稍微更新(脏)的代码,它也不起作用。 现在只有一个文件:

var InputList = React.createClass({ 

    getInitialState: function() { 
     return { 
      rowCount: 1 
     } 
    }, 

    getClassNames: function() { 
     if (this.props.type === 'incomes') { 
      return 'col-md-4 ' + this.props.type; 
     } else if (this.props.type === 'expenses') { 
      return 'col-md-4 col-md-offset-1 ' + this.props.type; 
     } 
    }, 

    addRow: function() { 
     this.state.rowCount = this.state.rowCount + 1; 
     this.render(); 
    }, 

    render: function() { 
     var inputs = []; 
     for (var i=0;i<this.state.rowCount; i++) { 
      inputs.push(i); 
     } 

     console.log(inputs); 

     return (
      <div className={ this.getClassNames() }> 
       {inputs.map(function (result) { 
        return <InputRow key={result} />; 
       })} 
       <div className="row"> 
        <button onClick={this.addRow} className="btn btn-success">Add more</button>  
       </div> 
      </div> 
     ); 
    } 
}); 

回答

4

this.render()什么也没做。如果你看看函数,它只是做一些计算并返回一些数据(虚拟DOM节点)。

你应该使用setState而不是直接修改它。这是更清洁的,并允许做出反应,以了解事情的变化。

addRow: function() { 
    this.setState({rowCount: this.state.rowCount + 1}); 
}, 
+0

太棒了,这个工作。谢谢。 – matiit 2014-11-23 19:11:34

0

不要将组件列表存储在状态中。 取而代之的是存储收入行数和费用行数。 使用点击处理程序来增加这些计数。 使用渲染方法根据计数生成所需的行。

+0

我做您的评论之前,类似的事情只是几分钟: * https://gist.github.com/matiit/f2cf0059dec0a4054cb2 * https://gist.github.com/matiit/a3665b0725b16cc4a7b3 隐而不宣也不行。 – matiit 2014-11-23 18:18:29