React - onClick事件不起作用

时间:2017-02-05 21:04:36

标签: javascript reactjs

我刚刚开始学习React.js,目前我正在研究简单的“待办事项”应用程序。我在提交按钮上遇到onClick事件的问题,它似乎不起作用。我认为将道具传递给父元素时遇到了问题。

这是我的代码:

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>

我真的很感激任何帮助,因为我一直试图解决这个问题。

1 个答案:

答案 0 :(得分:0)

你没有调用这个函数:

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

您也可以这样写:

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