Javascript React Js 有条件地应用类属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30533171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Js conditionally applying class attributes
提问by apexdodge
I want to conditionally show and hide this button group depending on what is passed in from the parent component which looks like this:
我想根据从父组件传入的内容有条件地显示和隐藏此按钮组,如下所示:
<TopicNav showBulkActions={this.__hasMultipleSelected} />
....
....
__hasMultipleSelected: function() {
return false; //return true or false depending on data
}
....
....
var TopicNav = React.createClass({
render: function() {
return (
<div className="row">
<div className="col-lg-6">
<div className="btn-group pull-right {this.props.showBulkActions ? 'show' : 'hidden'}">
<button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
Bulk Actions <span className="caret"></span>
</button>
<ul className="dropdown-menu" role="menu">
<li><a href="#">Merge into New Session</a></li>
<li><a href="#">Add to Existing Session</a></li>
<li className="divider"></li>
<li><a href="#">Delete</a></li>
</ul>
</div>
</div>
</div>
);
}
});
Nothing is happening however, with the {this.props.showBulkActions ? 'show' : 'hidden'}. Am I doing anything wrong here?
然而,{this.props.showBulkActions 没有发生任何事情?'显示':'隐藏'}。我在这里做错了什么吗?
回答by spitfire109
The curly braces are inside the string, so it is being evaluated as string. They need to be outside, so this should work:
花括号在字符串内部,因此它被评估为字符串。他们需要在外面,所以这应该有效:
<div className={"btn-group pull-right " + (this.props.showBulkActions ? 'show' : 'hidden')}>
Note the space after "pull-right". You don't want to accidentally provide the class "pull-rightshow" instead of "pull-right show". Also the parentheses needs to be there.
注意“右拉”后的空格。您不想意外地提供类“pull-rightshow”而不是“pull-right show”。括号也需要在那里。
回答by Diego V
As others have commented, classnamesutility is the currently recommended approach to handle conditional CSS class names in ReactJs.
正如其他人评论的那样,类名实用程序是当前推荐的在 ReactJs 中处理条件 CSS 类名的方法。
In your case, the solution will look like:
在您的情况下,解决方案将如下所示:
var btnGroupClasses = classNames(
'btn-group',
'pull-right',
{
'show': this.props.showBulkActions,
'hidden': !this.props.showBulkActions
}
);
...
...
<div className={btnGroupClasses}>...</div>
As a side note, I would suggest you to try to avoid using both showand hiddenclasses, so the code could be simpler. Most likely you don't need to set a class for something to be shown by default.
作为旁注,我建议您尽量避免同时使用show和hidden类,这样代码会更简单。很可能您不需要为默认显示的内容设置类。
回答by Bertrand
If you are using a transpiler (such as Babelor Traceur) you can use the new ES6 "template strings".
如果您使用的是转译器(例如Babel或 Traceur),您可以使用新的 ES6 “模板字符串”。
Here is the answer of @spitfire109, modified accordingly:
这是@spitfire109 的回答,做了相应修改:
<div className={`btn-group pull-right ${this.props.showBulkActions ? 'shown' : 'hidden'}`}>
This approach allows you to do neat things like that, rendering either s-is-shownor s-is-hidden:
这种方法允许你做这样的整洁的事情,呈现s-is-shown或s-is-hidden:
<div className={`s-${this.props.showBulkActions ? 'is-shown' : 'is-hidden'}`}>
回答by Musa
You can use here String literals
您可以在这里使用字符串文字
const Angle = ({show}) => {
const angle = `fa ${show ? 'fa-angle-down' : 'fa-angle-right'}`;
return <i className={angle} />
}
回答by flaky
Expending on @spitfire109's fine answer, one could do something like this:
花在@spitfire109 的好答案上,你可以做这样的事情:
rootClassNames() {
let names = ['my-default-class'];
if (this.props.disabled) names.push('text-muted', 'other-class');
return names.join(' ');
}
and then within the render function:
然后在渲染函数中:
<div className={this.rootClassNames()}></div>
keeps the jsx short
保持 jsx 简短
回答by Pencilcheck
Or use npm classnames. It is very easy and useful especially for constructing the list of classes
或者使用 npm类名。它非常容易和有用,特别是对于构建类列表
回答by Eugene Chybisov
In case you will need only one optional class name:
如果您只需要一个可选的类名:
<div className={"btn-group pull-right " + (this.props.showBulkActions ? "show" : "")}>
回答by Tudor Morar
You can use ES6 arrays instead of classnames. The answer is based on Dr. Axel Rauschmayer article: Conditionally adding entries inside Array and object literals.
您可以使用 ES6 数组代替类名。答案基于 Axel Rauschmayer 博士的文章:有条件地在 Array 和 object literals 中添加条目。
<div className={[
"classAlwaysPresent",
...Array.from(condition && ["classIfTrue"])
].join(" ")} />
回答by pery mimon
2019:
2019年:
React is lake a lot of utilities. But you don't need any npmpackage for that . just create somewhere the function classnamesand call it when you need;
React 是许多实用程序的湖。但是你不需要任何npm包。只需在某处创建函数classnames并在需要时调用它;
function classnames(obj){
return Object.entries(obj).filter( e => e[1] ).map( e=>e[0] ).join(' ');
}
or
或者
function classnames(obj){
return Object.entries(obj).map( ([k,v]) => v?k:'' ).join(' ');
}
example
例子
stateClass= {
foo:true,
bar:false,
pony:2
}
classnames(stateClass) // return 'foo pony'
<div className="foo bar {classnames(stateClass)}"> some content </div>
Just For Inspiration
只为灵感
declare helper element and used it togglemethod
声明辅助元素并使用它的toggle方法
(DOMToken?List)classList.toggle(class,condition)
(DOMToken?List)classList.toggle(class,condition)
example:
例子:
const classes = document.createElement('span').classList;
function classstate(obj){
for( let n in obj) classes.toggle(n,obj[n]);
return classes;
}
回答by Nate Ben
More elegant solution, which is better for maintenance and readability:
更优雅的解决方案,更利于维护和可读性:
const classNames = ['js-btn-connect'];
if (isSelected) { classNames.push('is-selected'); }
<Element className={classNames.join(' ')}/>

