簡體   English   中英

觸發ReactJS元素的onClick事件

[英]Trigger onClick event for a ReactJS element

我有一個用reactjs加載的元素列表,在該列表的末尾有一個按鈕,可通過使用reactjs的onclick事件加載更多項目。

我想創建一個使用javascript或jquery的函數,觸發onclick事件以加載所有項目,而不是在加載更多項目上一個接一個地單擊。

我嘗試使用jquery中的間隔來執行此操作,但是$element.trigger('click')無法正常工作,什么也不做。

誰能幫我這個? 請。

ReactJS:

var ConversationShowMore = React.createClass({
    getInitialState: function(){
        return {show: false, next_comments: ""};
    },
    loadMoreComments: function(){
        this.setState({show: true});
    },
    render: function(){
        var obj = this.props.next_comments || "";
        if (obj != "" && requesturl != obj) {
            if (this.state.show) {
                return (
                    <ConversationBox url={this.props.next_comments} />
                )
            }else{
                return (
                    <a onClick={this.loadMoreComments} className="showmoreconversations" href="#" role="button"><span>Load more conversations...</span></a>
                )
            }
        }else{
            return (
                <div></div>
            )
        }
    }
});

Javascript / jQuery:

    var tid = setInterval(myCode, 5000);
    function myCode() {
        if($("#conversationContainer a.showmoreconversations").length){
            $("#conversationContainer a.showmoreconversations").trigger('click');
        }else{
            abortTimer();
        }
    }
    function abortTimer() {
        clearInterval(tid);
    }

裝入組件后,您將觸發請求以加載更多注釋。 此請求完成后,您將在X毫秒內安排另一個請求。

loadMoreComments(){
    console.log('loaded more comments');
  // Probably, you will trigger async request. Call following line when this request is complete.
  this.timeout = window.setTimeout(this.loadMoreComments, 5000);
},

componentDidMount() {
    this.loadMoreComments();
},

卸載組件時,請記住要取消預定的請求。 否則,它將幾乎永遠運行(並且肯定會拋出異常)

componentWillUnmount() {
    window.clearTimeout(this.timeout);
},

這里的工作示例: https//jsfiddle.net/69z2wepo/34030/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM