[英]React onClick function not firing
I have a React component that houses several Post components. 我有一个React组件,其中包含几个Post组件。 I have onClick attributes on every Post component which should fire a simple console.log.
我在每个Post组件上都有onClick属性,应该会触发一个简单的console.log。 I have no idea why it is not firing.
我不知道为什么它不射击。 Here is the code.
这是代码。
class Feed extends Component {
constructor(){
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
console.log('hello');
}
render(){
return(
<div className='feed_container'>
<h2 className='feed_header_text'>Followed Posts <i className="fa fa-address-book" aria-hidden="true"></i></h2>
<Post name='Bruce Banner' onClick={this.handleClick}/>
<Post name='Peter Parker' onClick={this.handleClick}/>
<Post name='Bruce Wayne' onClick={this.handleClick}/>
<Post name='Harleen Frances Quinzel' onClick={this.handleClick}/>
<Post name='Alan Scott' onClick={this.handleClick}/>
<Post name='Tony Stark' onClick={this.handleClick}/>
<Post name='Clark Kent' onClick={this.handleClick}/>
<Post name='Barry Allen' onClick={this.handleClick}/>
</div>
);
}
}
You can not bind the onClick
or any other event to component.You should bind it to DOM element. 您不能将
onClick
或任何其他事件绑定到组件。应将其绑定到DOM元素。
<Post name='Bruce Banner' onClick={this.handleClick}/> //wrong
instead, 代替,
define the Post
in such way,so it accept eventHanlder as props and attach it to Post
DOM element. 以这种方式定义
Post
,以便它接受eventHanlder作为props并将其附加到Post
DOM元素。
Post component : 职位组成:
const Post = ({handleClick})=>(<div onClick={handleClick}>Hello</div>)
passed handleClick
to Post component : 通过
handleClick
to Post组件:
<Post name='Bruce Banner' handleClick={this.handleClick}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.