2016-12-02 22 views
0

我是新来的反应,JS,我需要在部件的方法结合一些澄清没有参数的道具方法并没有得到子组件称为反应

我有2个部件为父级和ChildComponent

var ParentComponent = React.createClass({ 

methodArg: function (value) { 
    console.log("methodArg called", value); 
}, 

methodNoArg: function() { 
    console.log("methodNoArg called"); 
}, 

render: function() { 
    return <ChildComponent m1={(value) => this.methodArg(value)} m2={() => this.methodNoArg} /> 
} 

}) 

儿童

var ChildComponent = React.createClass({ 
render: function() { 
    return (
     <div> 
      <button onClick={()=>this.props.m1(100)}>Call M1</button> 
      <button onClick={()=>this.props.m2()}>Call M2</button> 
     </div> 
    ) 
} 
}) 

当我点击呼叫M1按钮,methodArg()母公司获取调用。

但是当我点击致电M2methodNoArg()没有被调用。这有什么问题?

当我通过methodNoArg于儿童,它获取调用

<ChildComponent m1={this.methodArg()} m2={this.methodNoArg} /> 

methodArg()获取调用没有点击该按钮,它获取调用每次当子组件呈现。

+0

你缺少'()''后this.methodNoArg' - 'this.methodNoArg'返回指针'function',你还是要调用它 – pwolaq

回答

0
<button onClick={()=>this.props.m1(100)}>Call M1</button> 

你上面一行是说评估M1方法和分配结果的onClick。所以,当你刷新你的页面时,你的console.log语句中你传递的值会被打印出来,但无论你点击多少次,onClick现在都没有方法赋值,它将永远不会被再次调用。

您可以通过删除自动调用该方法的括号而不点击来实现所需的功能。

这里工作的jsfiddle代码链接: http://jsfiddle.net/fp0LvkLg/

+0

箭头函数只是一种绑定方式。 {this.props.m1.bind(this,100)}与{()=> this.props.m1(100)}相同。在你的jsfiddle代码中。尝试删除绑定并检查。方法m1将在单击按钮之前调用。 John

+0

检查这个http://jsfiddle.net/john1jan/nu6ydt09/1/ – John

+0

你是对的,有微不足道的区别箭头和绑定,除非你不能使用新的n更多的箭头。但在你上面的jsfiddle中,如果我正确地检查,你是没有约束力的。 – Vikas

1

这是因为您将其分配方法的道具

m2={() => this.methodNoArg}

是(那种,如果我们忽略的this复杂性),相当于

m2={function() {return this.methodNoArg}}

这样的方式你的道具是一个函数,它返回一个函数,而函数又不会被调用。

你想简单的功能分配给这样的道具:

m2={this.methodNoArg}

+0

但我在子节点this.props.m2()中调用方法m2。哪个是方法调用? – John

+0

你的意思是有一个函数只返回方法对象的函数。 如果我调用this.props.m2()它返回this.methodNoArg,但不调用methodNoArg? – John

+0

是的,这就是发生了什么 – Mchl