我目前正在使用React.js重寫我的一個Web應用程序(使用jQuery和JavaScript製作)以使用React.js。React中的classNames的複雜條件
我在處理複雜條件語句時遇到了一些小問題,如何渲染className。
我在名爲AppContainer的主要組件類中有兩個狀態叫做userChoseToMeetAlien
和cupAndSaucerHaveArrived
。
userChoseToMeetAlien
和cupAndSaucerHaveArrived
布爾值的初始狀態設置爲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.userChoseToMeetAlien
和props.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>
);
}
我很感激任何幫助。由於
這是完美的。很棒!謝謝 :) – Sarah