简体   繁体   English

React + jQuery -> 按钮 onClick 不起作用

[英]React + jQuery -> Button onClick is not working

Using ReactJS and jQuery I am adding buttons dynamically to specific div id's in my component like so:使用 ReactJS 和 jQuery,我将按钮动态添加到组件中的特定 div id,如下所示:

$('id_name').html('<button>..text..</button>);

However, each of these buttons needs to have onClick functionality, and that is where my problem is.但是,这些按钮中的每一个都需要具有 onClick 功能,这就是我的问题所在。

The code that I need help with is this:我需要帮助的代码是这样的:

export default React.createClass({

        ....

    for(var i = 0; i<this.state.cells.length; i++){
          var id = '#'+this.state.cells[i];
          var mb = $(id).text();
          if(mb.length==0){
            $(id).html("<div id='"+ id +"' class='time-slot'> \
                            <button onClick="+this.buttonActivated()+"> \
                                <span id='message-"+id+"'>Not Assigned</span> \
                            </button> \
                       </div>");
          }
    }

         ....

    buttonActivated: function(){
        console.log("Button Clicked");
    },

         ....

});

What is actually happening is that when this page renders the function is run automatically for every button that is rendered, so I am getting 15 console logs saying "Button Clicked", but when I click any of the buttons the function is not triggered.实际发生的情况是,当此页面呈现时,该功能会针对呈现的每个按钮自动运行,因此我收到 15 个控制台日志,显示“已单击按钮”,但是当我单击任何按钮时,该功能不会被触发。

You should not insert DOM element into another DOM element like this in React.在 React 中,您不应该像这样将 DOM 元素插入到另一个 DOM 元素中。 You should render it via JSX and also remove the parentheses from the function.您应该通过 JSX 渲染它并从函数中删除括号。 in your constructor, add :在您的构造函数中,添加:

this.buttonActivated = this.buttonActivated.bind(this)

in your if statement do:在你的 if 语句中:

if(mb.length==0){
            $(id).html(<div id={idAsAParam} className="time-slot"> 
                      <button onClick={this.buttonActivated}> 
                           <span id={"message-"+idAsAParam}>Not Assigned</span> 
                      </button>
                </div>);
          }

This is only a pseudo suggestion to insert html/element into another DOM object.这只是将 html/element 插入另一个 DOM 对象的伪建议。 I would suggest doing the insertion via a state change within the render function of your component.我建议通过组件渲染函数中的状态更改来进行插入。

This way react will be aware of the click event to listen to.这样,react 就会知道要收听的点击事件。

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

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