我想要做一個表單,可以添加/刪除行通過點擊添加/刪除按鈕。我現在的問題是,刪除按鈕總是可以刪除最後一行,而不是刪除按鈕所在的行。當我使用數組刪除操作符時,它可以刪除所需的行。然而,這種方法並沒有真正刪除數組中的對象,並且可能很難在for循環中進行檢查。我想知道我在哪裏做錯了?更新 - 動態添加/刪除行不按預期工作
更新時間: 1.增加的jsfiddle https://jsfiddle.net/69z2wepo/84246/ 2.保存下拉值母公司的狀態
constructor(props){
super(props)
this.state = {
dropdown: [
{first: "true", hideAdd: "false", result: ""}
]
}
this.addRow = this.addRow.bind(this);
this.removeRow = this.removeRow.bind(this);
this.onChange = this.onChange.bind(this);
}
onChange = (key, value) => {
let oldArray = JSON.parse(JSON.stringify(this.state.dropdown));
oldArray[key]['result'] = value;
this.setState({dropdown:oldArray}, function(){
console.log(this.state.dropdown);
//console.log(this.state.dropdown.length)
})
}
removeRow = (e, key) => {
e.preventDefault();
let oldArray = JSON.parse(JSON.stringify(this.state.dropdown));
oldArray.slice();
oldArray.splice(key, 1);
for (let i=0; i<oldArray.length; i++){
if (i==0){
oldArray[i]['first'] = 'true';
}
if (oldArray.length==1){
oldArray[i]['hideAdd'] = 'false';
}else{
oldArray[i]['hideAdd'] = 'true';
if (i == oldArray.length-1){
oldArray[i]['hideAdd'] = 'false';
}
}
}
this.setState({dropdown:oldArray}, function(){
console.log(this.state.dropdown);
//console.log(oldArray);
//console.log(oldArray.length);
})
}
render() {
return (
<Grid.Column>
<Grid style={comStyles().gridWidth}>
<Grid.Row>
<Grid.Column width={4} textAlign='left' style={comStyles().lineHeight}>Then</Grid.Column>
<Grid.Column width={12}>
{
this.state.dropdown.map((item, index) => (
<RulesThenDropdown default={item.result} onChange={this.onChange} add={this.addRow} remove={this.removeRow} id={index} key={index} hideAdd={item.hideAdd} first={item.first} />
))
}
</Grid.Column>
</Grid.Row>
</Grid>
</Grid.Column>
)
}
而以下是從子組件的代碼
render() {
const Options = thenOptions;
let extra = "";
const removeBtn = <button onClick={(e,m)=>this.props.remove(e,this.props.id)} className="circular ui icon button"><i className="icon minus"></i></button>
const addBtn = <button onClick={(e,m)=>this.props.add(e,this.props.id)} className="circular ui icon button"><i className="icon plus"></i></button>
if(this.props.first==="false"){
if(this.props.hideAdd=="true"){
extra = removeBtn;
}else{
extra = <div>{addBtn}{removeBtn}</div>;
}
}else if(this.props.first==="true"){
if(this.props.hideAdd!="true"){
extra = addBtn;
}else{
extra = removeBtn;
}
}
return (
<div style={comStyles().buttonsMainWrapper}>
<Form.Dropdown
placeholder='Then'
fluid
selection
options={Options}
defaultValue = {this.props.result}
onChange={(e,{ value })=>this.props.onChange(this.props.id, value)}
/>
<div style={comStyles().buttonsGroup}>
{
extra
}
</div>
</div>
)
}
一個很好的替代陣列中的端部,這個問題是這行'oldArray.splice(key,1);'?您是否嘗試過'console.log'並檢查前後的'oldArray'值? –
嗨Firice,是的,數組似乎是正確的 – HUNG
'splice'和'delete'之間'oldArray'的結果是一樣的嗎?如果在'oldArray = oldArray.filter(n => n)'之後使用'delete'並清理'oldArray'' –