当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - ReactJS & Google MDL Button onClick not working

问题描述:

I have some JS like below. I find that if I remove mdl-js-layout the onClick of the button works. Otherwise it fails. Why might this be? I have already did componentHandler.upgradeDom()

'use strict';

module.exports = React.createClass({

componentDidMount: function() {

console.log('update')

componentHandler.upgradeDom();

},

addExpense: function() {

console.log('add expense');

},

render: function() {

return (

<div ref="appLayout" className="mdl-layout mdl-js-layout mdl-layout--fixed-drawer">

<div className="mdl-layout__drawer">

<span className="mdl-layout-title">Expenses</span>

<nav className="mdl-navigation">

<a className="mdl-navigation__link" href="#">Expenses</a>

<a className="mdl-navigation__link" href="#">Settings</a>

</nav>

</div>

<main className="mdl-layout__content">

<div className="page-content">

<div className="mdl-grid">

<div className="mdl-cell mdl-cell--12-col">

<button ref="btnAddExpense" onClick={this.addExpense} className="mdl-button mdl-js-button mdl-button--raised mdl-button--accent">

Add Expense

</button>

</div>

</div>

</div>

</main>

</div>

);

}

});

If I look into the React debugger tools, I can actually see the onClick is supposed to be bound?

网友答案:

It looks like mdl is not compatible with react, and prevents the click events from the react component from working. Hopefully, this would be fixed in a future update, but until then, you can work around this by manually re-adding the events after mounting the component.

componentDidMount: function() {
  componentHandler.upgradeDom();
  var button = this.refs.btnAddExpense;
  button.addEventListener('click', this.addExpense);
},

Demo

网友答案:

Hopefully this answers your question: With the resources used it apparently does not need to touch the DOM.

HTML
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js">
</script>

<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>

JS
var Widget = React.createClass({
  handleBtnClick: function(e) {
    e.preventDefault();
    alert("clicked!");
    return true;
  },

  render: function() {
    return <div >
      <form>
        < button className = "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-textfield--full-width mdl-button--facebook"
          onClick = {
            this.handleBtnClick
          } >
          Click MEEEEEE!
        < /button >  </form> < /div >;
     }
  });

  ReactDOM.render( < Widget / > ,
  document.getElementById('container')
);
分享给朋友:
您可能感兴趣的文章:
随机阅读: