我开始学习 React,但遇到了第一堵墙。
我有一个列表组件,它应该显示行列表+用于添加新行的按钮。
一切都在这两个要点中:
https://gist.github.com/matiit/7b361dee3f878502e10a
https://gist.github.com/matiit/8bac28c4d5c6ce3993c7
addRow方法在点击时执行,因为我可以看到console.log,但没有添加InputRow。
实在不明白为什么。
这是一些更新的(脏)代码,但也不起作用。 现在只有一个文件:
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>
);
}
});
最佳答案
this.render()
不执行任何操作。如果您查看该函数,它只是进行一些计算并返回一些数据(虚拟 dom 节点)。
您应该使用 setState 而不是直接修改它。这更干净,并且允许 react 知道某些内容发生了变化。
addRow: function () {
this.setState({rowCount: this.state.rowCount + 1});
},
关于reactjs - React,在组件中添加组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091082/