为什么onclick事件被解雇

时间:2018-04-10 15:49:34

标签: reactjs const bind

以下reactjs工作正常。我想知道是否有可能将onDelete prop更改为只是todo.id然后以某种方式调用removeTodo方法,换句话说有没有办法将App.removeTodo绑定到const Todo?

所以我玩了一下并做了两处改动:

const Todo = props =>(

<li>
 <input type='checkbox' checked={props.todo.checked} onChange={props.onToggle} />
 <button onClick={props.onDelete.removeTodo(props.todo.id)}>Delete</button>
 <span>{props.todo.text}</span>
</li>

然后:

<Todo
   key={todo.id}
   todo={todo}
   onToggle={()=>(this.checkBox(todo.id))}
   onDelete={this}
/>

问题是每当我们添加Todo

时都会触发removeTodo

&#13;
&#13;
import React from "react"
import "./App.css"

let id=0
const Todo = props =>(
  <li>
     <input type='checkbox' checked={props.todo.checked} onChange={props.onToggle} />
     <button onClick={props.onDelete}>Delete</button>
     <span>{props.todo.text}</span>
  </li>
)
class App extends React.Component{
  constructor(){
    super()
    this.state={
      todos:[]
    }
  }

  addTodo(e){
     this.setState({todos: [...this.state.todos,{
                               id:id++,
                               text:e.target.value,
                               checked:false}
                            ]
     })
     e.target.value=''
  }

  checkBox(id){
    this.setState({todos: this.state.todos.map(todo=>{
         if(todo.id !== id)return todo
         return{
           id:id,
           text:todo.text,
           checked: !todo.checked
         }
    })})
  }
  removeTodo(id){
    this.setState({todos: this.state.todos.filter(todo=>(todo.id !==id))})
  }

  render(){
    return(
      <div>
         <span>Count of Todos: &nbsp; {this.state.todos.length}</span>
         <input type='text' placeholder='add Todos'
            onKeyPress={((e)=>(e.key==='Enter') ? this.addTodo(e):null)}/>
         <span>Checked Todos: &nbsp;
            {this.state.todos.filter(todo=>(todo.checked === true)).length}
         </span>

         <ul>
            {this.state.todos.map(todo=>(
             <Todo
                key={todo.id}
                todo={todo}
                onToggle={()=>(this.checkBox(todo.id))}
                onDelete={function(){this.removeTodo(todo.id)}.bind(this)}
             />
            ))}
         </ul>
      </div>
    )
  }

}


export default App
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

问题是您在Todo渲染时立即调用remove todo,请参阅:

    <button onClick={props.onDelete.removeTodo(props.todo.id)}>Delete</button>

尝试传递函数而不是调用它:

    <button onClick={() => props.onDelete.removeTodo(props.todo.id)}>Delete</button>