[英]ReactJS onClick doesn't trigger
I'm having trouble getting onClick
working in reactJS. 我在使
onClick
在reactJS中工作时遇到麻烦。 I put together this fiddle and am sure its something trivial. 我整理了这个小提琴,并确定它是微不足道的。 Code is below, see fildle for (not)working example:
代码如下,请参阅fildle以获取(不起作用的)示例:
var Bar=React.createClass({
render: function() {
return (
<div className="bar" style={{width: this.props.width+"px"}}> {this.props.width}</div>)
}
})
var ClickableBar=React.createClass({
clickBar: function(e) {
alert('clicked');
this.setState({width:220});
},
render: function() {
return (
<Bar onClick={this.clickBar} width={this.state.width}/>
)
}
})
ReactDOM.render(
<ClickableBar width="20"/>,
document.getElementById('container')
);
You just need to pass the handler through as a prop: 您只需要通过处理程序作为道具:
var Bar = React.createClass({
render: function() {
return (
<div onClick={this.props.onClick} className="bar" style={{width: this.props.width+"px"}}>{this.props.width}</div>
);
}
});
Otherwise, your div will be created without a click listener on it, since a "Bar" doesn't really exist in the dom (only the div is actually there). 否则,将在您的div上创建没有单击侦听器的div,因为dom中实际上并不存在“ Bar”(只有div实际上存在)。
And you also missed to initialize your state
而且您也错过了初始化
state
getInitialState: function(){
return {
width: 30
}
}
Otherwise you will get an error 否则你会得到一个错误
Uncaught TypeError: Cannot read property 'width' of null
未捕获的TypeError:无法读取null的属性“ width”
I prefer using style in this way 我更喜欢用这种方式
render(){
var myStyle = {width: 200, backgroundColor: green};
return <div style={myStyle }> ... </div>
}
It also works with React. 它也可以与React一起使用。
Fiddle example
Thanks 谢谢
You just need to bind the function with the DOM element. 您只需要将函数与DOM元素绑定即可。
<Bar onClick={this.clickBar.bind(this)} width={this.state.width}/>
or 要么
<Bar onClick={() => {this.clickBar()}} width={this.state.width}/>
If you want to call function by passing the event: 如果要通过传递事件来调用函数:
<select onClick = {(event) => {self.funcName(event)}} >
If you want to call function by passing arguments: 如果要通过传递参数来调用函数:
<select onClick = {(event) => {self.funcName(event, arg1)}} >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.