元素可以通过以下几种方式实现:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
items: ['item1', 'item2', 'item3']
};
}
handleDelete = (item) => {
this.setState(prevState => ({
items: prevState.items.filter(i => i !== item)
}));
}
render() {
return (
<div>
{this.state.items.map(item => (
<div key={item}>
{item}
<button onClick={() => this.handleDelete(item)}>删除</button>
</div>
))}
</div>
);
}
}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
items: ['item1', 'item2', 'item3']
};
}
handleDelete = (index) => {
this.setState(prevState => {
const items = [...prevState.items];
items.splice(index, 1);
return { items };
});
}
render() {
return (
<div>
{this.state.items.map((item, index) => (
<div key={item}>
{item}
<button onClick={() => this.handleDelete(index)}>删除</button>
</div>
))}
</div>
);
}
}
以上是在React中删除元素的几种常见方式,具体使用哪种方式取决于具体的需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云