【问题标题】:onClick listener not firing in reactonClick 侦听器未在反应中触发
【发布时间】:2018-08-11 13:20:27
【问题描述】:

我正在尝试制作一个简单的待办事项应用程序来响应,并且我正试图删除项目。所以我在我的 App.js 文件中创建了一个removeTodo 方法。 我有一个 todoList 组件,它遍历 state.todos 中的todosarray,然后注入todocomponent。虽然我正在寻找一种可以将 removeTodo 函数向下传递给 todo 组件的方法。这是我的尝试...

 removeTodo(){
//just need this function to fire
console.log("1234")

}

 render() {

return (
  <div className="App">

   <div className="header">
    <h1>Todo Application</h1>
   </div>

   <div className="header">
    <input
    type="text"
    ref={((ref) => this.input = ref)}
    value={this.state.todoText}
    onKeyPress={this.handleSub.bind(this)}
    />
   </div>
   <TodoList todos={this.state.todos} remove={this.removeTodo.bind(this)}/>
   //passing in removeTodo method to props       
  </div>
);
}

这是我的 todoList 组件

function todoList(props){

return (

<ul className="todoList">

{props.todos.map((todo, index) => {
    return(
    <Todo onClick={props.remove} name={todo.name} key={index}/>
    //the todo component just renders an li with the name inside the todos 
      array
    );
})}

</ul>

);

}

每当我点击渲染的 Todo 时,什么都没有发生,为什么 onClick 没有触发?我是新来的,对于任何无知提前做出反应非常抱歉

【问题讨论】:

  • onClick 将与提供给Todo 组件的任何其他道具一样,因此您还需要在onClick 道具上添加this.props.onClick Todo 中的元素。
  • 我有点明白你,但你能提供一个例子吗?我会投票

标签: javascript reactjs


【解决方案1】:

onClick 将与提供给Todo 组件的任何其他道具一样,因此您还需要将道具中的onClick 函数添加到onClickTodo 元素上的道具。

示例

function TodoList(props) {
  return (
    <ul className="todoList">
      {props.todos.map((todo, index) => (
        <Todo
          onClick={() => console.log(`Clicked ${index}!`)}
          name={todo.name}
          key={index}
        />
      ))}
    </ul>
  );
}

function Todo(props) {
  return <li onClick={props.onClick}>{props.name}</li>;
}

ReactDOM.render(
  <TodoList todos={[{ name: "foo" }, { name: "bar" }]} />,
  document.getElementById("root")
);
<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="root"></div>

【讨论】:

  • 太好了,太完美了!谢谢
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2019-11-09
  • 1970-01-01
  • 2013-08-22
  • 2015-12-27
相关资源
最近更新 更多