我有这样一个需求:
表格里面td包着input,点击+号就新增一行,现在要做验证是否为空,具体是这样:
点击+号之后,先检查上一行是否全都填写:
若是,新增一行且上一行的input使用readOnly=true禁止修改,
若否,就弹窗提示让他输入
现在我是在componentDidUpdate里判断prevState和getState的表格行数,然后在里面加readOnly,但是二者竟然始终相等,这是为什么?
另一个问题:我引用上一行的input值时,怎么比较方便?
我现在是想给每一个input一个ref,这个ref由行号和表头组成,
例如第一行第一列就是1_key,然后在addRow里面用这个ref来引用,有更好的思路吗?
代码:
MyRow是被添加的行的组件,addRow是添加事件
var MyRow = React.createClass({
getInitialState:function(){
return{
rowkey:"",
rowType:"",
rowRefer:"",
rowNote:"",
}
},
render:function(){
return(
<tr>
<td><input ref="xx" type="text" name="rowkey" value={this.state.rowkey} onChange={this::handleChange} className="tableInpt" /></td>
<td><input type="text" name="rowType" value={this.state.rowType} onChange={this::handleChange} className="tableInpt" /></td>
<td><input type="text" name="rowRefer" value={this.state.rowRefer} onChange={this::handleChange} className="tableInpt" /></td>
<td><input type="text" name="rowNote" value={this.state.rowNote} onChange={this::handleChange} className="tableInpt" /></td>
</tr>
);
}
})
var SelectTemplateDialogBody = React.createClass({
getInitialState:function(){
return{
emptyRows:[],
}
},
addRow:function(){
let rows = this.state.emptyRows;
rows.push(<MyRow key={this.state.emptyRows.length} />);
this.setState({emptyRows:rows});
},
componentDidUpdate:function(prevProps,prevState){
console.log("update");
console.log(this.state.emptyRows);
console.log(prevState.emptyRows);
if(this.state.emptyRows.length>prevState.emptyRows.length){
console.log("readonly");
this.refs.xx.readOnly = true;
}
},
render:function(){
return(
<div key="mytableContent" className="mg35">
<table className="table table-mystriped">
<tbody>
<tr>
<th>Key</th>
<th>Type</th>
<th>Reference</th>
<th>Note</th>
</tr>
{this.state.emptyRows}
</tbody>
</table>
<div className="addRow" onClick={this.addRow}>+</div>
<div className="btn-fld">
<button id="newTableBtn" className="tableBtn" type="submit">保存模板</button>
<button id="cancelTableBtn" className="tableBtn cancelBtn" type="submit">取消</button>
</div>
</div>
)
}
});