我正在使用React.js动态创建一个包含文本框的html表。我有可以通过单击按钮删除的行。我希望,当我在第一行上单击“删除”时,该表将重新渲染,而第一行已删除。但是,当react重新绘制表格时,看起来它总是从DOM中删除表格的最后一行,而不是使用state
对象的实际值。也许我发现了一个错误?这是我的代码:
/** @jsx React.DOM */
var MyApp = React.createClass({
getInitialState: function () {
return {
col_one: ['c1r1', 'c1r2', 'c1r3'],
col_two: ['c2r1', 'c1r2', 'c1r3'],
col_three: ['c3r1', 'c3r2', 'c3r3']
}
},
handleCellChange: function (colName, index, e) {
console.log('onChange:', colName, index, e.target.value);
},
handleRemove: function (i) {
var that = this;
console.log('removing row:',i);
_.forEach(this.state, function (val, colName) {
that.state[colName].splice(i,1); // BUG???
//_.pullAt(that.state[key], i); // doesn't work either
});
console.log(this.state);
this.setState(this.state);
},
render: function() {
var that = this,
rows = [],
cols = _.keys(this.state);
rows.push(
<tr>
{cols.map(function (col) {
return (
<th>{col}</th>
)
})}
</tr>
)
for (var i = 0; i < this.state[cols[0]].length; i++) {
rows.push(
<tr>
{cols.map(function (col) {
return (
<td>
<input type="text" defaultValue={that.state[col][i]} onChange={that.handleCellChange.bind(that, col, i)} />
</td>
)
})}
<td>
<button onClick={this.handleRemove.bind(this, i)}>Remove</button>
</td>
</tr>
)
}
return (
<table>
<tbody>
{rows}
</tbody>
</table>
);
}
});
React.renderComponent(<MyApp />, document.body);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句