提问者:小点点

React onClick函数在呈现时激发


我将2个值传递给子组件:

  1. 要显示的对象列表
  2. 删除函数。

我使用.map()函数来显示我的对象列表(就像react教程页面中给出的示例),但是该组件中的按钮在呈现时激发onclick函数(它不应该在呈现时激发)。我的代码如下所示:

module.exports = React.createClass({
    render: function(){
        var taskNodes = this.props.todoTasks.map(function(todo){
            return (
                <div>
                    {todo.task}
                    <button type="submit" onClick={this.props.removeTaskFunction(todo)}>Submit</button>
                </div>
            );
        }, this);
        return (
            <div className="todo-task-list">
                {taskNodes}
            </div>
        );
    }
});

我的问题是:为什么onclick函数在render时触发,以及如何使它不触发?


共1个答案

匿名用户

因为您正在调用该函数,而不是将该函数传递给onClick,所以将该行更改为:

<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>

=>称为箭头函数,该函数在ES6中引入,将在React 0.13.3或更高版本中得到支持。