我有一个简单的表单,我想在其中单击“删除”按钮时删除所选的项目。我正在部分删除所需的项目,但是如果我删除中间的项目,它也会删除最后一个项目。如果我删除第一个项目,它将删除整个数组。
代码在这里:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: ["Saab", "Volvo", "BMW"],
editMode: false,
rulesTerm: ""
};
}
handleInput = e => {
let value = e.target.value;
let name = e.target.name;
console.log(name);
console.log(value);
this.setState(prevState => ({
data: {
...prevState.data,
[name]: value
}
}));
};
handleFormSubmit = e => {
e.preventDefault();
const { data } = this.state;
console.log(data);
};
removeRule = (e, index) => {
e.preventDefault();
const { data } = this.state;
console.log("removed", data.splice(index));
this.setState({
data: data,
rulesTerm: ""
});
};
render() {
return (
<div className="App">
<div>
{!this.state.editMode ? (
<button onClick={() => this.setState({ editMode: true })}>
edit
</button>
) : (
<div>
<button onClick={() => this.setState({ editMode: false })}>
cancel
</button>
<button onClick={this.handleFormSubmit}>submit</button>
</div>
)}
</div>
<React.Fragment>
{this.state.data.map((rule, index) =>
this.state.editMode ? (
<form onSubmit={this.handleFormSubmit}>
<React.Fragment>
<input
onChange={this.handleInput}
type="text"
placeholder="Cars"
name={rule}
defaultValue={rule}
key={index}
/>
<button onClick={event => this.removeRule(event, index)}>
Remover
</button>
</React.Fragment>
</form>
) : (
<p key={rule}> - {rule} </p>
)
)}
</React.Fragment>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
有帮助吗? 谢谢!
答案 0 :(得分:5)
使用splice
时,您需要输入要删除的元素数量。
如果省略deleteCount,或者其值等于或大于array.length-开始(即,如果等于或大于数组中剩余的元素数量,则从start开始),然后从数组开始到结尾的所有元素都将被删除。
答案 1 :(得分:0)
一种解决方案是将删除函数转换为咖喱函数,该函数将在调用一次后首先收到index
,然后再接收该事件。
您可以使用setState
的回调版本过滤出元素,并过滤出具有相同索引的元素:
removeRule = index => event => {
this.setState(prev => ({
data: prev.data.filter((el, i) => i !== index),
rulesTerm: ""
}));
};
您还可以指示您的splice
方法只需要删除一个元素即可:
removeRule = index => event => {
this.setState(prev => ({
data: prev.data.splice(index, 1),
rulesTerm: ""
}));
};
您在JSX中的函数绑定现在将如下所示:
<button onClick={this.removeRule(index)}>
Remover
</button>
答案 2 :(得分:0)
在您的情况下,我将使用过滤器,并将规则作为参数传递:
<React.Fragment>
{this.state.data.map((rule, index) =>
this.state.editMode ? (
<form onSubmit={this.handleFormSubmit}>
<React.Fragment>
<input
onChange={this.handleInput}
type="text"
placeholder="Cars"
name={rule}
defaultValue={rule}
key={index}
/>
<button onClick={event => this.removeRule(event, rule)}>
Remover
</button>
</React.Fragment>
</form>
) : (
<p key={rule}> - {rule} </p>
)
)}
</React.Fragment>
比于removeRule函数:
removeRule = (e, rule) => {
e.preventDefault();
const { data } = this.state;
const newData = data.filter(item => item !== rule);
console.log("removed");
this.setState({
data: newData,
rulesTerm: ""
});
};