我创建了一个简单的表单,该表单在表单下方显示输入数据,我想为其添加2种功能:
class App extends React.Component {
state = { value: "", items: [] };
handleChange = e => {
this.setState({ value: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
this.setState({ items: [this.state.value, ...this.state.items] });
this.setState({ value: "" });
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input value={this.state.value} onChange={this.handleChange} />
<button>submit</button>
</form>
<ul>
{this.state.items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}
}
// eg. add 1 to [3, 2, 1] => [1, 3, 2]
答案 0 :(得分:0)
在设置值时使用过滤器删除该值,如下所示:
class App extends React.Component {
state = { value: "", items: [] };
handleChange = e => {
this.setState({ value: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
this.setState({
value:"",
items: [this.state.value, ...this.state.items.filter(val => val !== this.state.value)]
});
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input value={this.state.value} onChange={this.handleChange} />
<button>submit</button>
</form>
<ul>
{this.state.items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}
}
答案 1 :(得分:0)
您可以通过合并当前项和新值来获得唯一数组,如下所示:
const { value } = this.state;
const currentItems = [...this.state.items];
const items = [...new Set([...currentItems, ...value])];
您可以在这里找到有效的演示:https://codesandbox.io/s/n5l3v6r3km