我将两个值传递给子组件:
我使用.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
函数在渲染时触发,以及如何使其不触发?
发布于 2015-11-22 02:02:19
因为您调用的是该函数,而不是将函数传递给onClick,所以将该行更改为:
<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>
=>
调用箭头函数,该函数是在ES6中引入的,将在React 0.13.3或更高版本上支持。
发布于 2015-11-22 02:00:57
不调用函数,而是将值绑定到函数:
this.props.removeTaskFunction.bind(this, todo)
参考文献:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
发布于 2015-11-22 02:01:16
onClick
属性的值应该是函数,而不是函数调用。
<button type="submit" onClick={function(){removeTaskFunction(todo)}}>Submit</button>
https://stackoverflow.com/questions/33846682
复制相似问题