我的问题与Button Tag中的一行代码有关。
let content = this.props.searchResult.map((ele, i) => {
let card_id = ele.user.username + "_card";
return(
<div className="col s12 m6 l4" key={i} id={card_id}>
<div className="card hoverable">
<ProfileCard user={ele} eleIndex ={i} searchUserLevel={this.props.searchUserLevel}/>
<div className="card-action">
<button className="btn waves-effect waves-light orange"
type="submit" name="action" onClick={ this.addPotentialClient(ele.user.username) } >
Add<i className="material-icons right">add</i>
</button>
</div>
</div>
</div>);
});
在上面的代码中加载页面后,onClick操作会从Button标签触发。
使用下面的代码,onClick操作仅在单击时触发,这是所需的属性。
let content = this.props.searchResult.map((ele, i) => {
let card_id = ele.user.username + "_card";
return(
<div className="col s12 m6 l4" key={i} id={card_id}>
<div className="card hoverable">
<ProfileCard user={ele} eleIndex ={i} searchUserLevel={this.props.searchUserLevel}/>
<div className="card-action">
<button className="btn waves-effect waves-light orange"
type="submit" name="action" onClick={ () => {this.addPotentialClient(ele.user.username)} } >
Add<i className="material-icons right">add</i>
</button>
</div>
</div>
</div>);
});
函数调用之间究竟有什么区别?
答案 0 :(得分:2)
在第二个区块中
onClick={ () => {this.addPotentialClient(ele.user.username)} }
这相当于:
var that = this;
...
onClick={function() {that.addPotentialClient(ele.user.username)} }
然而,第一个块是
onClick={ this.addPotentialClient(ele.user.username) }
相当于:
var value = this.addPotentialClient(ele.user.username);
...
onClick={ value }