[英]Complex conditionals for classNames in React
I am currently re-writing one of my Web applications (made using jQuery and JavaScript) to use React.js instead. 我目前正在重写我的一个Web应用程序(使用jQuery和JavaScript制作)以使用React.js代替。
I am having a little trouble figuring out how to render classNames when working with a complex conditional statement. 我在弄清楚如何使用复杂的条件语句时呈现类名称时遇到了一些麻烦。
I have two states called userChoseToMeetAlien
and cupAndSaucerHaveArrived
in my main component class called AppContainer. 我有两个状态称为
userChoseToMeetAlien
和cupAndSaucerHaveArrived
我叫AppContainer主要组件类。
The initial state of the userChoseToMeetAlien
and cupAndSaucerHaveArrived
booleans are set to false as follows. userChoseToMeetAlien
和cupAndSaucerHaveArrived
布尔值的初始状态设置为false,如下所示。
constructor(props) {
super(props);
this.state = {
userChoseToMeetAlien: false,
cupAndSaucerHaveArrived: false
};
}
I have a stateless component called CupAndSaucer
and these states (mentioned above) are passed in as properties. 我有一个名为
CupAndSaucer
的无状态组件,并且这些状态(上述)作为属性传递。
I would like to add different classes to the HTML (rendered in CupAndSaucer
) depending on the values of these properties. 我想根据这些属性的值向HTML添加不同的类(在
CupAndSaucer
呈现)。
Here is the pseudocode of how I would like things to work: 这是我希望事情如何工作的伪代码:
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
Here is my CupAndSaucer
component where I have attempted to add the classes. 这是我尝试添加类的
CupAndSaucer
组件。 As you can see it is not ideal as the full_position
class is added when both props.userChoseToMeetAlien
and props.cupAndSaucerHaveArrived
are false. 如您所见,当
props.userChoseToMeetAlien
和props.cupAndSaucerHaveArrived
均为false时,添加了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>
);
}
I'd appreciate any help. 我将不胜感激。 Thanks
谢谢
Try this awesome library https://github.com/JedWatson/classnames Something like this: 试试这个很棒的库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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.