简体   繁体   English

如何在元件上添加onClick

[英]How to add onClick on the component

I am using https://github.com/winhtaikaung/react-tiny-link for displaying some posts from other blogs.我正在使用https://github.com/winhtaikaung/react-tiny-link来显示来自其他博客的一些帖子。 I am able to get the previews correctly.我能够正确获得预览。 I want to capture the views count through onClick() but this module(react-tiny-link) doesn't seems to support the same, please help.我想通过 onClick() 捕获视图计数,但是这个模块(react-tiny-link)似乎不支持相同的,请帮忙。

<ReactTinyLink
cardSize="large"
showGraphic={true}
maxLine={0}
minLine={0}
header={""}
description={""}
url={url}
onClick={() => this.handleViewCount(id)} />

I tried adding div around the component but it affects the css.我尝试在组件周围添加 div,但它会影响 css。

You can wrap your link with a div and attach your onClick callback on that div instead.您可以用div包装您的链接,并在该div上附加您的onClick回调。

<div onClick={() => this.handleViewCount(id)}>
  <ReactTinyLink
    cardSize="large"
    showGraphic={true}
    maxLine={0}
    minLine={0}
    header={""}
    description={""}
    url={url}
  />
</div>

Your library - ReactTinyLink does not support onClick attribute.您的库 - ReactTinyLink 不支持 onClick 属性。 Since you've tagged javascript - I can give you a small JS hack for the same.既然你已经标记了 javascript - 我可以给你一个小的 JS hack。

Run the following code at the end of your React Rendering在 React 渲染结束时运行以下代码

var cards = document.getElementsByClassName('react_tinylink_card');
linksClicked = [];

for(var i = 0; i<cards.length; i++){
    cards[i].onclick = function(){
        linksClicked.push(this.href);
    }
}

The above code will go through each and every cards and will attach onClick handlers on them, once clicked - the 'this' object will be your anchor tag's element, so I am storing it's href.上面的代码将 go 通过每张卡,并将在其上附加 onClick 处理程序,一旦单击 - 'this' object 将是您的锚标签的元素,所以我存储它(you're free to store anything you want) (你可以自由存储任何你想要的东西)

In the following example - https://winhtaikaung.github.io/react-tiny-link/ I tried the same snippet - and got the following result在以下示例中 - https://winhtaiikaung.github.io/react-tiny-link/我尝试了相同的片段 - 并得到以下结果在此处输入图像描述

Hope this would be a good starting point for what you're trying to achieve.希望这将是您要实现的目标的良好起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM