我有一个绑定到onClick
组件的currentAreas
处理程序。调用onClick
组件时会同时调用currentAreas
处理程序,但之后不起作用。
onClick
不起作用,我认为这可能是由于我绑定onClick
函数的方式。
currentAreas.js
import React, { Component, PropTypes } from 'react';
export default class currentAreas extends Component {
constructor(props) {
super(props);
}
render() {
const { onClick } = this.props;
return(
<div className="list-group panel">
<a href="#demo3" className="list-group-item" onClick={onClick("All", "All")} >All</a>
</div>
);
}
}
currentList.js(主要组件)
class currentList extends Component {
constructor(props) {
super(props);
this.updateLocation = this.updateLocation.bind(this);
}
updateLocation(name, nameLocation){
console.log(name);
console.log(nameLocation);
}
render() {
return (
<div className="step-3-container">
<CurrentAreas
onClick ={this.updateLocation} />
</div>
)
}
}
答案 0 :(得分:2)
每当你的javascript解释器“看到”一个“()”时,它就会尝试执行“()”之前的函数。因此,您的代码实际执行的是执行 onClick
(来自props
的那个),作为参数传递“All”和“All”。所以,你需要做的是,不要自己调用它,让onClick
处理程序调用它。
换句话说,onClick
道具必须收到function
。
一种可能的解决方案是将onClick
包装成箭头函数,执行类似的操作:
<a href="#demo3" onClick={() => onClick("All", "All")}>All</a>
或者,您可以bind
函数的参数(bind返回一个函数,因此它很适合onClick
)。
<a href="#demo3" onClick={onClick.bind(null, "All", "All")}>All</a>
第一个bind
参数是绑定函数内的this
值。
FMI约为bind
:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
答案 1 :(得分:1)
您在组件声明期间执行该功能,这可能意味着您在渲染时触发它,而不是单击
Command="{Binding View.DataContext.Max}"
需要
onClick={onClick("All", "All")}
或
onClick={onClick.bind(null, "All", "All")}
react组件的onClick={function(){ onClick("All", "All"); }}
需要一个可以执行的回调。你正在传递onClick
的返回值,因为你立即用参数