Javascript 在 React 中处理条件样式的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35762351/
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
Correct way to handle conditional styling in React
提问by davidhtien
I'm doing some React right now and I was wondering if there is a "correct" way to do conditional styling. In the tutorial they use
我现在正在做一些 React,我想知道是否有一种“正确”的方式来做条件样式。在他们使用的教程中
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
I prefer not to use inline styling so I want to instead use a class to control conditional styling. How would one approach this in the React way of thinking? Or should I just use this inline styling way?
我不喜欢使用内联样式,所以我想使用类来控制条件样式。人们将如何以 React 的思维方式来解决这个问题?或者我应该只使用这种内联样式方式?
采纳答案by David L. Walsh
If you prefer to use a class name, by all means use a class name.
如果您更喜欢使用类名,请务必使用类名。
className={completed ? 'text-strike' : null}
You may also find the classnamespackage helpful. With it, your code would look like this:
您可能还会发现classnames包很有帮助。有了它,您的代码将如下所示:
className={classNames({ 'text-strike': completed })}
There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.
没有“正确”的方式来做条件样式。做最适合你的事情。就我自己而言,我更喜欢避免内联样式并以刚刚描述的方式使用类。
POSTSCRIPT [06-AUG-2019]
后记 [06-AUG-2019]
Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled componentsor emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.
虽然 React 对样式没有偏见,但现在我会推荐 CSS-in-JS 解决方案;即样式组件或情感。如果您是 React 的新手,请坚持使用 CSS 类或内联样式。但是一旦您对 React 感到满意,我建议您采用这些库之一。我在每个项目中都使用它们。
回答by Abhay Shiro
<div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>
Checkout the above code. That will do the trick.
检查上面的代码。这样就行了。
回答by Vlado
If you need to conditionally apply inline styles (apply all or nothing) then this notation also works:
如果您需要有条件地应用内联样式(应用全部或不应用),则此表示法也适用:
style={ someCondition ? { textAlign:'center', paddingTop: '50%'} : {}}
In case 'someCondition' not fulfilled then you pass empty object.
如果 'someCondition' 未满足,则传递空对象。
回答by S McCrohan
First, I agree with you as a matter of style - I would also (and do also) conditionally apply classes rather than inline styles. But you can use the same technique:
首先,我同意你的风格 - 我也会(并且也会)有条件地应用类而不是内联样式。但是您可以使用相同的技术:
<div className={{completed ? "completed" : ""}}></div>
For more complex sets of state, accumulate an array of classes and apply them:
对于更复杂的状态集,累积一组类并应用它们:
var classes = [];
if (completed) classes.push("completed");
if (foo) classes.push("foo");
if (someComplicatedCondition) classes.push("bar");
return <div className={{classes.join(" ")}}></div>;
回答by hawkEye
instead of this:
而不是这个:
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
you could try the following using short circuiting:
您可以使用短路尝试以下操作:
style={{
textDecoration: completed && 'line-through'
}}
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
key bit of information from the link:
来自链接的关键信息:
Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
短路意味着在 JavaScript 中,当我们评估 AND 表达式 (&&) 时,如果第一个操作数为假,JavaScript 将短路,甚至不会查看第二个操作数。
It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.
值得注意的是,如果第一个操作数为假,这将返回假,因此可能必须考虑这将如何影响您的风格。
The other solutions might be more best practice, but thought it would be worth sharing.
其他解决方案可能是更多的最佳实践,但认为值得分享。
回答by Denis S Dujota
I came across this question while trying to answer the same question. McCrohan's approach with the classes array & join is solid.
我在尝试回答同一问题时遇到了这个问题。McCrohan 使用类数组和连接的方法是可靠的。
Through my experience, I have been working with a lot of legacy ruby code that is being converted to React and as we build the component(s) up I find myself reaching out for both existing css classes and inline styles.
根据我的经验,我一直在处理许多被转换为 React 的遗留 ruby 代码,当我们构建组件时,我发现自己接触了现有的 css 类和内联样式。
example snippet inside a component:
组件内的示例片段:
// if failed, progress bar is red, otherwise green
<div
className={`progress-bar ${failed ? failed' : ''}`}
style={{ width: this.getPercentage() }}
/>
Again, I find myself reaching out to legacy css code, "packaging" it with the component and moving on.
再次,我发现自己接触了遗留的 css 代码,将它与组件“打包”并继续前进。
So, I really feel that it is a bit in the air as to what is "best" as that label will vary greatly depending on your project.
所以,我真的觉得什么是“最好的”有点悬而未决,因为该标签会因您的项目而有很大差异。
回答by diegocl02
Another way, using inline style and the spread operator
另一种方式,使用内联样式和扩展运算符
style={{
...completed ? { textDecoration: completed } : {}
}}
That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.
这种方式在某些情况下很有用,您希望根据条件同时添加一堆属性。
回答by Snivio
the best way to handle styling is by using classes with set of css properties.
处理样式的最佳方法是使用具有一组 css 属性的类。
example:
例子:
<Component className={this.getColor()} />
getColor(){
let class = "badge m2";
class + = this.state.count===0?"wrarning":danger
return class
}