React onClick 函数在渲染时触发 [英] React onClick function fires on render
问题描述
我将 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:
- List of objects to display
- 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屋!