简体   繁体   English

反应-onClick事件不起作用

[英]React - onClick event not working

I've just started learning React.js and currently I'm working on simple "to do" app. 我刚刚开始学习React.js,目前我正在开发简单的“要做”应用程序。 I have encountered problem with onClick event on my submit button, it doesn't seem to work. 我在提交按钮上的onClick事件遇到了问题,它似乎不起作用。 I think I have got a problem with passing props to parent elements. 我认为将道具传递给父元素时遇到问题。

Here is my code: 这是我的代码:

 var Application = React.createClass ({ getInitialState: function() { return { title: "Your to do list", subTitle: "What do you have to do?", tasks: [], } }, addTask: function(event) { event.preventDefault(); alert("it works!"); }, removeTask: function() { var taskList = this.state.tasks; var currentTask = taskList.find(function(task) { return task.key == event.target.key; }); currentTask.remove(); event.preventDefault(); alert("it works!"); }, render: function() { return ( <div className="app-container"> <Header title={this.state.title} /> <NewTaskForm subTitle={this.state.subTitle} onChange= {this.addTask} /> <TaskContainer tasks={this.state.tasks} /> </div> ); } }); function Header(props) { return ( <div className="app-title"> <h1>{props.title}</h1> </div> ); } function NewTaskForm(props) { return ( <div className="new-task-area"> <form> <label for="new-task">{props.subTitle}</label> <input type="text" id="new-task" placeholder="Type in task" /> <button type="submit" onClick={function() {props.onChange;}}>Add task!</button> </form> </div> ); } NewTaskForm.propTypes = { onChange: React.PropTypes.func.isRequired, }; function TaskContainer(props) { return ( <div className="new-task-container"> {props.tasks.map(function(task) { return ( <p key={task.key}>{task.text}</p> ); })} </div> ); } ReactDOM.render(<Application />, document.getElementById("container")); 
 <!DOCTYPE html> <html> <head> <title>React to do app!</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet"> <link rel="stylesheet" href="css/style.css" type="text/css" /> </head> <body> <div id="container"></div> <script type="text/javascript" src="js/react.js"></script> <script type="text/javascript" src="js/react-dom.js"></script> <script type="text/javascript" src="js/babel-browser.min.js"></script> <script type="text/babel" src="js/app.jsx"></script> </body> </html> 

I would really appreciate any help because I've been trying to solve this for some time now. 非常感谢您的帮助,因为我已经尝试解决了一段时间。

you didn't call the function: 您没有调用该函数:

<button type="submit" onClick={function() {props.onChange();}}>Add task!</button>

you can also write it like this: 您也可以这样写:

<button type="submit" onClick={props.onChange}>Add task!</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM