gpt4 book ai didi

javascript - ReactJS 如何从列表中删除项目

转载 作者:数据小太阳 更新时间:2023-10-29 03:59:55 26 4
gpt4 key购买 nike

我有创建 <li> 的代码元素。我需要通过单击一个一个地删除元素。对于每个元素,我都有 Delete button .我知道我需要一些功能来通过 id 删除项目.如何执行此功能以删除 ReactJS 中的元素?我的代码:

class TodoApp extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {items: [], text: ''};
}

render() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.handleChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
);
}

handleChange(e) {
this.setState({text: e.target.value});
}

handleSubmit(e) {
e.preventDefault();
var newItem = {
text: this.props.w +''+this.props.t,
id: Date.now()
};
this.setState((prevState) => ({
items: prevState.items.concat(newItem),
text: ''
}));
}

delete(id){ // How that function knows id of item that need to delete and how to delete item?
this.setState(this.item.id)
}
}

class TodoList extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}<button onClick={this.delete.bind(this)}>Delete</button></li>
))}
</ul>
);
}
}

最佳答案

您在父组件中管理数据并在子组件中呈现 UI,因此要从子组件中删除项目,您需要将函数与数据一起传递,从子组件调用该函数并传递列表项的任何唯一标识符,在父组件中删除使用该唯一标识符的项目。

第 1 步:从父组件传递一个函数和数据,如下所示:

<TodoList items={this.state.items} _handleDelete={this.delete.bind(this)}/>

第二步:在父组件中定义delete函数,如下所示:

delete(id){
this.setState(prevState => ({
data: prevState.data.filter(el => el != id )
}));
}

第 3 步:使用 this.props._handleDelete() 从子组件调用该函数:

class TodoList extends React.Component {

_handleDelete(id){
this.props._handleDelete(id);
}

render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}<button onClick={this._handleDelete.bind(this, item.id)}>Delete</button></li>
))}
</ul>
);
}
}

检查这个工作示例:

class App extends React.Component{
constructor(){
super();
this.state = {
data: [1,2,3,4,5]
}
this.delete = this.delete.bind(this);
}

delete(id){
this.setState(prevState => ({
data: prevState.data.filter(el => el != id )
}));
}

render(){
return(
<Child delete={this.delete} data={this.state.data}/>
);
}
}

class Child extends React.Component{

delete(id){
this.props.delete(id);
}

render(){
return(
<div>
{
this.props.data.map(el=>
<p onClick={this.delete.bind(this, el)}>{el}</p>
)
}
</div>
)
}
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

关于javascript - ReactJS 如何从列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com