[英]onClick listener not firing in react
I'm trying to make a simple todo app in react and am at the point where I am trying to delete items. 我正在尝试制作一个简单的待办事项应用程序作为响应,并且正要删除项目。 So I have created a
removeTodo
method in my App.js file. 因此,我在App.js文件中创建了
removeTodo
方法。 I have a todoList component which loops through the todos
array in the state.todos and then injects the todo
component. 我有一个todoList组件,该组件在state.todos中遍历
todos
数组,然后注入todo
组件。 Although I am looking at a way in which I can pass the removeTodo function down to the todo component. 尽管我正在寻找一种方法,可以将removeTodo函数向下传递给todo组件。 Here is my attempt at doing this...
这是我这样做的尝试...
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>
);
}
Here's my todoList Component 这是我的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>
);
}
Whenever I go to click on the rendered Todo nothing happens, why is the onClick not firing? 每当我单击渲染的Todo时,什么都没有发生,为什么onClick不触发? I'm new to react so sorry in advance for any ignorance
我是新来的,因此对您的无知事先表示抱歉
onClick
will be like any other prop given to the Todo
component, so you need to add the onClick
function in the props to a onClick
prop on an element in Todo
as well. onClick
就像提供给Todo
组件的任何其他道具一样,因此您还需要将道具中的onClick
函数添加到Todo
元素上的onClick
道具中。
Example 例
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.