简体   繁体   中英

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. I can't seem to get an onClick event to fire. 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. Do I have to do this in JSX?

Actually I found the solution. As you may know if a callback returns false normally you have to put inside an onclick attribute

return mycallbackfunction();

with this code I had to use 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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