简体   繁体   English

不使用JSX的onClick

[英]React onClick without JSX

I have a special application of React to get working where I would prefer not to use JSX and Where I need to monitor clicks on links outside of React. 我有一个特殊的React应用程序,可以在不希望使用JSX的地方以及需要监视React外部链接的点击的地方开始工作。 I can't seem to get an onClick event to fire. 我似乎无法触发onClick事件。 The code I have needs to render the link inactive for the page it's on.` 我需要的代码使链接所在的页面处于非活动状态。

var LinkCell = React.createClass({
      render: function(){
        var attr = {
          "data-id":this.props.dataID,
          "href": this.props.href,
          "onClick": function(){return false}
        };
        var lnk = React.DOM.a(attr,this.props.href);

        return React.DOM.td({},lnk);
      }
    });

This doesn't work and the link goes to the URL in the href. 这不起作用,链接指向href中的URL。 Do I have to do this in JSX? 我必须在JSX中执行此操作吗?

Actually I found the solution. 其实我找到了解决方案。 As you may know if a callback returns false normally you have to put inside an onclick attribute 您可能知道,如果回调通常返回false,则必须将onclick属性放入其中

return mycallbackfunction();

with this code I had to use preventDefault();. 使用此代码,我必须使用preventDefault();。 I don't know why I didn't try it before but thanks for the replies. 我不知道为什么我以前没有尝试过,但感谢您的答复。

var LinkCell = React.createClass({
      render: function(){
        var attr = {
          "data-id":this.props.dataID,
          "href": this.props.href,
          onClick:function(e){e.preventDefault();}
        };
        var lnk = React.DOM.a(attr,this.props.href);

        return React.DOM.td({},lnk);
      }
    });

i found the best solution for this 我找到了最好的解决方案

 //like_button.js 'use strict'; const e = React.createElement; class LikeButton extends React.Component { constructor(props) { super(props); this.state = { liked: false }; } render() { if (this.state.liked) { return 'You liked this.'; } return e( 'button', { onClick: () => this.setState({ liked: true }) }, 'Click This' ); } } const domContainer = document.getElementById('domContainer'); ReactDOM.render(e(LikeButton), domContainer); 
 <!-- index.html --> <!DOCTYPE html> <html> <body> <div id="domContainer"></div> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="like_button.js"></script> </body> </html> 

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

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