2016-02-10 122 views
14

在我的React組件中,我有一個按鈕意味着點擊時通過AJAX發送一些數據。我只需要第一次發生,即在第一次使用後禁用按鈕。ReactJs:防止多次按下按鈕

如何我試圖做到這一點:

var UploadArea = React.createClass({ 

    getInitialState() { 
    return { 
     showUploadButton: true 
    }; 
    }, 

    disableUploadButton(callback) { 
    this.setState({ showUploadButton: false }, callback); 
    }, 

    // This was simpler before I started trying everything I could think of 
    onClickUploadFile() { 
    if (!this.state.showUploadButton) { 
     return; 
    } 
    this.disableUploadButton(function() { 
     $.ajax({ 
     [...] 
     }); 

    }); 
    }, 

    render() { 
    var uploadButton; 
    if (this.state.showUploadButton) { 
     uploadButton = (
     <button onClick={this.onClickUploadFile}>Send</button> 
    ); 
    } 

    return (
     <div> 
     {uploadButton} 
     </div> 
    ); 
    } 

}); 

我認爲發生的是狀態變量showUploadButton沒有更新向右走,該文檔做出反應說,預計。

我該如何強制執行按鈕才能禁用或在被點擊的瞬間全部離開?

回答

14

你可以做的是使按鈕被禁用後,單擊,並將其保留在頁面(不可點擊的元素)。

要做到這一點,你必須一個引用添加到該按鈕元素

<button ref="btn" onClick={this.onClickUploadFile}>Send</button> 

,然後在onClickUploadFile功能禁用按鈕

​​

然後,您可以相應樣式禁用的按鈕給一些反饋給用戶

.btn:disabled{ /* styles go here */} 

如果需要請確保reen能夠將其與

this.refs.btn.removeAttribute("disabled"); 

更新:處理裁判的最佳方式作出反應是一個功能,而不是一個字符串。

<button 
    ref={btn => { this.btn = btn; }} 
    onClick={this.onClickUploadFile} 
>Send</button> 


this.btn.setAttribute("disabled", "disabled"); 
this.btn.removeAttribute("disabled"); 

這裏是一個小例子使用 https://jsfiddle.net/69z2wepo/30824/

+0

這讓我走了一半,但做出反應小組已棄用給裁判一個字符串值,而是與它一起使用回調:https://reactjs.org/docs/refs-and-the-dom.html – Martin

8

測試作爲工作一個你提供的代碼:http://codepen.io/zvona/pen/KVbVPQ

class UploadArea extends React.Component { 
    constructor(props) { 
    super(props) 

    this.state = { 
     isButtonDisabled: false 
    } 
    } 

    uploadFile() { 
    // first set the isButtonDisabled to true 
    this.setState({ 
     isButtonDisabled: true 
    }); 
    // then do your thing 
    } 

    render() { 
    return (
     <button 
     type='submit' 
     onClick={() => this.uploadFile()} 
     disabled={this.state.isButtonDisabled}> 
     Upload 
     </button> 
    ) 
    } 
} 

ReactDOM.render(<UploadArea />, document.body); 
+1

這不會解決問題,因爲狀態更新被React消除。正因爲如此,'this.state.isButtonDisabled'中總會有延遲來獲得'false'值。快速連續點擊兩次仍然會註冊2個onClick事件。 – Awol