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

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

问题描述

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

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

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

module.exports = React.createClass({渲染:函数(){var taskNodes = this.props.todoTasks.map(function(todo){返回 (<div>{todo.task}<button type="submit" onClick={this.props.removeTaskFunction(todo)}>提交</button>

);}, 这个);返回 (<div className="todo-task-list">{任务节点}

);}});

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

解决方案

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

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

I pass 2 values to a child component:

  1. List of objects to display
  2. delete function.

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(it 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>
        );
    }
});

My question is: why does onClick function fire on render and how to make it not to?

解决方案

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>

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

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆