我是 React 的新手。我创建了一个按钮组件。该组件渲染出一个图像,我的目标是使用该图像作为最喜欢的按钮。现在我想做的就是当我单击图像时在控制台中记录一些内容。
我使用了handleClick 事件,但我认为这并不是那么简单,这是我的组件:
/**
* Renders the Favorite button
*/
export default class FavoriteButton extends React.Component
{
/**
* Favorite button constructor
*
* @param props
*/
constructor(props)
{
super(props);
this.state = {
header: "some header test data",
}
}
/**
* Handle a click event on a Favorite button
*/
handleClick()
{
console.log("hello there");
}
/**
* Renders the Favorite button
*/
render()
{
return(
<div className="favorite_button">
<img src="url" className="" alt="" />
<div>{this.state.header}</div>
</div>
);
}
}
如果有人能帮助我,那就太棒了!
我的最终目标是触发数据库操作来存储您喜欢的元素,但现在我只想记录一些内容:)
非常感谢!
最佳答案
您已将方法 handleClick
添加到组件,但必须将其分配给 event handler ,在本例中为 onClick
。
render()
{
return(
<div className="favorite_button">
<img onClick={this.handleClick} src="url" className="" alt="" />
<div>{this.state.header}</div>
</div>
);
}
如果您要在 handleClick
中使用 this
,则还必须将该方法绑定(bind)到实例。
constructor(props)
{
super(props);
this.state = {
header: "some header test data",
}
this.handleClick = this.handleClick.bind(this);
}
关于javascript - React 组件上的句柄点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39406823/