2016-12-21 50 views
2

我知道JQuery是ReactJS中的代碼異味,因爲它遍歷整個DOM來完成它的工作。但是,我發現一些地方很難不使用它。這是我希望儘可能找到更好方法的一個例子。如何避免ReactJS中的jQuery調用

我只是想顯示或隱藏基於字段是否被填充在一個div的消息...

的javascript:

if (this.props.loginInfo.userId === ''){ 
    $("#errorMessageDiv").attr('class', 'visible'); 
} else{ 
    $("#errorMessageDiv").attr('class', 'invisible'); 
} 

JSX:

<div id="errorMessageDiv" className="invisible"> 
    <h1 id="credentials" className="login-error-message">&nbsp;Please Enter Proper Credentials</h1> 
</div> 
+1

您應該通常通過綁定類來實現。 – SLaks

回答

5

我建議你看看classnames庫。

基本上它做了什麼,添加或刪除了你喜歡的類名,如果你有沒有條件的類名只是傳遞true。請參閱以下片段。

import classNames from 'classnames' 

<div 
    id="errorMessageDiv" 
    className={ classNames({ 
    'visible' : this.props.loginInfo.userId === '', 
    'invisible' : this.props.loginInfo.userId !== '', 
    'some-other-class-name' : your_condition, 
    'will-be-available-definetely' : true 
    }) } 
> 
    <h1 id="credentials" className="login-error-message">&nbsp;Please Enter Proper Credentials</h1> 
</div> 

如果你只有一個條件,你可以做到以下幾點:

import classNames from 'classnames' 

<div 
    id="errorMessageDiv" 
    className={ this.props.loginInfo.userId === '' ? 'visible' : 'invisible' } 
> 
    <h1 id="credentials" className="login-error-message">&nbsp;Please Enter Proper Credentials</h1> 
</div> 
+0

我喜歡這個!但是,如何才能在觸發點擊事件後觸發?那可能嗎?現在,當您加載頁面時,默認情況下登錄消息已存在。 – nikotromus

+0

管理一個事件看起來很複雜,超出範圍的樣式......感謝一羣FurkanO! – nikotromus

+1

嗯,你需要改變事件發生時的值,以便你的條件改變,最終你的類名改變。我看不到任何方式或需要。 – FurkanO

1

你必須定義當前的狀態如何呈現眼簾,讓你不得不條件綁定到的渲染錯誤消息。

var visibleClass = this.props.loginInfo.userId === '' ? 'visible' : 'invisible'; 
return <div id="errorMessageDiv" className={visibleClass}> 
    <h1 id="credentials" className="login-error-message">&nbsp;Please Enter Proper Credentials</h1> 
</div>