我一直在尝试学习 react 并遇到了障碍。在理解跨子组件传递道具与遇到的问题相关时遇到问题。我在从待办事项列表中删除项目时遇到问题,并且可以为我这辈子都知道错了。
import React, { Component } from 'react';
import Form from './components/Form';
import Todo from './components/Todo';
class App extends Component {
constructor(props){
super(props);
this.state = {
userInput: "",
todoList: []
}
this.onChange= this.onChange.bind(this);
this.addItem=this.addItem.bind(this);
this.handleDelete=this.handleDelete(this);
}
//update input state
onChange=(e)=>{
this.setState({
userInput: e.target.value
})
}
//update todo list
addItem=(e)=>{
e.preventDefault();
if(this.state.userInput!==""){
const userData={
//create a specific user id for each input
id: Math.random(),
value: this.state.userInput
}
const list=[...this.state.todoList];
list.push(userData);
//Reset userInput after inputing data
this.setState({
userInput: "",
todoList: list
})
}
}
//Deleting an item
handleDelete=(id)=>{
const list=[...this.state.todoList];
const updatedList=list.filter(item=>item.id!==id)
this.setState({
todoList:updatedList
})
}
render() {
return(
<div>
<h1>
My Todo List
</h1>
<Form value={this.state.userInput} onChange={this.onChange} onSubmit={this.addItem} />
<Todo list={this.state.todoList} onDelete={this.handleDelete}/>
</div>
)
}
}
export default App;
上面是父组件
import React, { Component } from 'react';
class Form extends Component {
render() {
return (
<div>
<form >
<input type="text" value={this.props.value} onChange={this.props.onChange}/><button className="btn btn-primary" type="submit" onClick={this.props.onSubmit}>add</button>
</form>
</div>
);
}
}
export default Form;
import React, { Component } from 'react';
class Todo extends Component {
render() {
const todos=this.props.list.map((item,index)=><li key={item.id}>{item.value} <i onClick={this.props.onDelete(item.id)} class="fas fa-trash"></i></li>)
return (
<div>
<ul>
{todos}
</ul>
</div>
);
}
}
export default Todo;
答案 0 :(得分:1)
你几乎猜对了。您需要为您的 onClick 处理程序提供回调。
您现在拥有的方式是为 onClick 处理程序提供运行该函数的结果。换句话说,每次渲染都会调用 onDelete
,并且 onClick
被赋予 onDelete
的返回值(未定义)。
你想给它自己的功能。只需将其更改为:
onClick={() => this.props.onDelete(item.id)}
编辑:您在绑定 this.handleDelete
时也犯了错误。应该是:
this.handleDelete = this.handleDelete.bind(this);
但你做到了:
this.handleDelete = this.handleDelete(this);
这就是您收到错误的原因。
答案 1 :(得分:1)
显然,您的 Todo
组件没有正确提供点击处理程序:
<i onClick={this.props.onDelete(item.id)} class="fas fa-trash"></i>
应该是:
<i onClick={() => this.props.onDelete(item.id)} class="fas fa-trash"></i>
原因是因为 onClick
需要一个函数并以这种方式传递它 onClick={this.props.onDelete(item.id)}
提供了 onDelete
函数的返回。