2017-07-23 31 views
0

我目前正在使用React.js重寫我的一個Web應用程序(使用jQuery和JavaScript製作)以使用React.js。React中的classNames的複雜條件

我在處理複雜條件語句時遇到了一些小問題,如何渲染className。

我在名爲AppContainer的主要組件類中有兩個狀態叫做userChoseToMeetAliencupAndSaucerHaveArrived

userChoseToMeetAliencupAndSaucerHaveArrived布爾值的初始狀態設置爲false,如下所示。

constructor(props) { 
     super(props); 
     this.state = { 
     userChoseToMeetAlien: false, 
     cupAndSaucerHaveArrived: false 
    }; 
} 

我有稱爲CupAndSaucer無國籍組分和這些狀態(上述)被傳遞在作爲屬性。

我想添加不同的類到HTML(呈現在CupAndSaucer)取決於這些屬性的值。

這裏是我怎麼想的事情上班僞代碼:

if(props.userChoseToMeetAlien is true AND props.cupAndSaucerHaveArrived is false) then 
    add the move_animation class 
else if(props.userChoseToMeetAlien is false AND props.cupAndSaucerHaveArrived is true) 
    add the full_position class 
else 
    //both properties are false 
    should have no classes 
end 

這裏是我的CupAndSaucer組件,我嘗試添加類。 正如你所看到的,它不是理想的,因爲當props.userChoseToMeetAlienprops.cupAndSaucerHaveArrived都是假時,full_position類被添加。

const CupAndSaucer = function(props) { 
    return (<div id="cup_and_saucer_container" 
       className={((props.userChoseToMeetAlien === true && props.cupAndSaucerHaveArrived === false) ? 'move_animation' : 'full_position')}>  
     </div> 
    ); 

} 

我很感激任何幫助。由於

回答

4

試試這個真棒庫https://github.com/JedWatson/classnames 事情是這樣的:

import cn from 'classnames'; 

const CupAndSaucer = function(props) { 

    const className = cn('some-default-class', { 
     'move_animation': (props.userChoseToMeetAlien === true && props.cupAndSaucerHaveArrived === false), 
     'full_position': (props.userChoseToMeetAlien === false && props.cupAndSaucerHaveArrived === false) 
    }); 
    return (<div id="cup_and_saucer_container" 
       className={className}>  
     </div> 
    ); 

} 
+0

這是完美的。很棒!謝謝 :) – Sarah