React onClick函数在渲染时触发 [英] React onClick function fires on render

查看:331
本文介绍了React onClick函数在渲染时触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I pass 2 values to a child component:


  1. 要显示的对象列表

  2. 删除功能。

我使用.map()函数显示我的对象列表(如反应教程页面中给出的示例) ),但该组件中的按钮在渲染时触发onClick函数(在渲染时不应触发)。我的代码如下所示:

I use a .map() function to display my list of objects(like in the example given in react tutorial page), but the button in that component fires the onClick function, on render(in should not fire on render time). My code looks like this:

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函数会在渲染时触发,以及如何使它不能。

My question is: Why does mine onClick function fire on render and how to make it not to.

推荐答案

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

Because you are calling that function instead of passing the function to onClick, change that line to this:

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

=> 名为Arrow Function,在ES6中引入,将在React 0.13.3或更高版本上得到支持。

=> called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.

这篇关于React onClick函数在渲染时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆