CSS React.js 内联样式最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26882177/
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 inline style best practices
提问by eye_mew
I'm aware that you can specify styles within React classes, like this:
我知道您可以在 React 类中指定样式,如下所示:
var MyDiv = React.createClass({
render: function() {
var style = {
color: 'white',
fontSize: 200
};
return <div style={style}> Have a good and productive day! </div>;
}
});
Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?
我应该以这种方式进行所有样式设置,并且在我的 CSS 文件中完全没有指定样式吗?
Or should I avoid inline styles completely?
还是我应该完全避免内联样式?
It seems odd and messy to do a little bit of both - two places would need to be checked when tweaking styling.
两者都做一点似乎很奇怪和混乱 - 调整样式时需要检查两个地方。
采纳答案by chantastic
There aren't a lot of "Best Practices" yet. Those of us that are using inline-styles, for React components, are still very much experimenting.
还没有很多“最佳实践”。我们这些使用内联样式的人,对于 React 组件,仍然在进行大量的试验。
There are a number of approaches that vary wildly: React inline-style lib comparison chart
有许多方法千差万别:React inline-style lib compare chart
All or nothing?
全有还是全无?
What we refer to as "style" actually includes quite a few concepts:
我们所说的“风格”其实包含了很多概念:
- Layout — how an element/component looks in relationship to others
- Appearance — the characteristics of an element/component
- Behavior and state — how an element/component looks in a given state
- 布局——一个元素/组件相对于其他元素的外观
- 外观——元素/组件的特征
- 行为和状态——元素/组件在给定状态下的外观
Start with state-styles
从状态样式开始
React is already managing the state of your components, this makes styles of state and behaviora natural fit for colocation with your component logic.
React 已经在管理组件的状态,这使得状态和行为的样式自然适合与组件逻辑的托管。
Instead of building components to render with conditional state-classes, consider adding state-styles directly:
与其构建组件以使用条件状态类进行渲染,不如考虑直接添加状态样式:
// Typical component with state-classes
<li
className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />
// Using inline-styles for state
<li className='todo-list__item'
style={(item.complete) ? styles.complete : {}} />
Note that we're using a class to style appearancebut no longer using any .is-
prefixed class for state and behavior.
请注意,我们使用一个类来设置外观样式,但不再使用任何.is-
前缀类来表示state 和 behavior。
We can use Object.assign
(ES6) or _.extend
(underscore/lodash) to add support for multiple states:
我们可以使用Object.assign
(ES6) 或_.extend
(underscore/lodash) 添加对多种状态的支持:
// Supporting multiple-states with inline-styles
<li 'todo-list__item'
style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>
Customization and reusability
定制化和可重用性
Now that we're using Object.assign
it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so: <TodoItem dueStyle={ fontWeight: "bold" } />
. Implemented like this:
现在我们正在使用Object.assign
它变得非常简单,使我们的组件可重用不同的样式。如果我们想覆盖默认的样式,我们可以在调用点道具这样做,就像这样:<TodoItem dueStyle={ fontWeight: "bold" } />
。像这样实现:
<li 'todo-list__item'
style={Object.assign({},
item.due && styles.due,
item.due && this.props.dueStyles)}>
Layout
布局
Personally, I don't see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I'd just use one.
就个人而言,我认为内联布局样式没有令人信服的理由。有许多很棒的 CSS 布局系统。我就用一个。
That said, don't add layout styles directly to your component. Wrap your components with layout components. Here's an example.
也就是说,不要将布局样式直接添加到您的组件中。用布局组件包裹你的组件。这是一个例子。
// This couples your component to the layout system
// It reduces the reusability of your component
<UserBadge
className="col-xs-12 col-sm-6 col-md-8"
firstName="Michael"
lastName="Chan" />
// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
<UserBadge
firstName="Michael"
lastName="Chan" />
</div>
For layout support, I often try to design components to be 100%
width
and height
.
对于布局支持,我经常尝试将组件设计为100%
width
和height
。
Appearance
外貌
This is the most contentious area of the "inline-style" debate. Ultimately, it's up to the component your designing and the comfort of your team with JavaScript.
这是“内联式”辩论中最具争议的领域。归根结底,这取决于您设计的组件以及您的团队对 JavaScript 的舒适度。
One thing is certain, you'll need the assistance of a library. Browser-states (:hover
, :focus
), and media-queries are painful in raw React.
有一件事是肯定的,你需要图书馆的帮助。浏览器状态 ( :hover
, :focus
) 和媒体查询在原始 React 中很痛苦。
I like Radiumbecause the syntax for those hard parts is designed to model that of SASS.
我喜欢Radium,因为这些难点的语法旨在模拟 SASS 的语法。
Code organization
代码组织
Often you'll see a style object outside of the module. For a todo-list component, it might look something like this:
通常你会在模块之外看到一个样式对象。对于待办事项列表组件,它可能如下所示:
var styles = {
root: {
display: "block"
},
item: {
color: "black"
complete: {
textDecoration: "line-through"
},
due: {
color: "red"
}
},
}
getter functions
吸气功能
Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:
向模板中添加一堆样式逻辑可能会有些混乱(如上所示)。我喜欢创建 getter 函数来计算样式:
React.createClass({
getStyles: function () {
return Object.assign(
{},
item.props.complete && styles.complete,
item.props.due && styles.due,
item.props.due && this.props.dueStyles
);
},
render: function () {
return <li style={this.getStyles()}>{this.props.item}</li>
}
});
Further watching
进一步观察
I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it's best to 'just use CSS'.
今年早些时候,我在 React Europe 上更详细地讨论了所有这些:内联样式以及何时最好“只使用 CSS”。
I'm happy to help as you make new discoveries along the way :) Hit me up -> @chantastic
我很高兴在您一路上有新发现时提供帮助:) 联系我 -> @chantastic
回答by anandharshan
The style attribute in React expect the value to be an object, ie Key value pair.
React 中的 style 属性期望值是一个对象,即键值对。
style = {}
will have another object inside it like {float:'right'}
to make it work.
style = {}
里面会有另一个对象{float:'right'}
让它工作。
<span style={{float:'right'}}>{'Download Audit'}</span>
Hope this solves the problem
希望这能解决问题
回答by Kyle Mathews
I use inline styles extensively within my React components. I find it so much clearer to colocate styles within components because it's always clear what styles the component does and doesn't have. Plus having the full power of Javascript at hand really simplifies more complex styling needs.
我在 React 组件中广泛使用内联样式。我发现在组件内并置样式非常清晰,因为组件具有和不具有哪些样式总是很清楚。此外,手头拥有 Javascript 的全部功能确实可以简化更复杂的样式需求。
I wasn't convinced at first but after dabbling in it for several months, I'm fully converted and am in process of converting all my CSS to inline or other JS-driven css methods.
起初我并不相信,但在涉足几个月后,我完全转换并且正在将我所有的 CSS 转换为内联或其他 JS 驱动的 css 方法。
This presentation by Facebook employee and React contributor "vjeux" is really helpful as well — https://speakerdeck.com/vjeux/react-css-in-js
此演示文稿被Facebook员工和应对贡献者“vjeux”是真正有用的,以及- https://speakerdeck.com/vjeux/react-css-in-js
回答by Brigand
The main purpose of the style attribute is for dynamic, state based styles. For example, you could have a width style on a progress bar based on some state, or the position or visibility based on something else.
style 属性的主要目的是用于动态的、基于状态的样式。例如,您可以根据某种状态在进度条上设置宽度样式,或者根据其他内容设置位置或可见性。
Styles in JS impose the limitation that the application can't provide custom styling for a reusable component. This is perfectly acceptable in the aforementioned situations, but not when you change the visible characteristics, especially color.
JS 中的样式强加了应用程序无法为可重用组件提供自定义样式的限制。这在上述情况下是完全可以接受的,但当您更改可见特征(尤其是颜色)时则不然。
回答by alex_1948511
James K Nelson in his letter "Why You Shouldn't Style React Components With JavaScript"states that there is no actually need of using inline styles with its downsides. His statement is that old boring css with less/scss is the best solution. The part of his thesises in favor to css:
James K Nelson 在他的信件“为什么你不应该使用 JavaScript 设计 React 组件的样式”中指出,实际上没有必要使用内联样式及其缺点。他的说法是,使用less/scss 的陈旧乏味的css 是最好的解决方案。他论文中赞成 css 的部分:
- extendable externally
- leverable (inline styles overleap everything)
- designer-friendly
- 可外部扩展
- 可杠杆(内联样式超越一切)
- 设计师友好
回答by Vivek Mehta
Styling in JSX is very similar to styling in HTML.
JSX 中的样式与 HTML 中的样式非常相似。
HTML Case:
HTML 案例:
div style="background-color: red; color: white"
div 样式 =“背景颜色:红色;颜色:白色”
JSX Case:
JSX 案例:
div style={{ backgroundColor: 'red', color: 'white' }}
div style={{ backgroundColor: 'red', color: 'white' }}
回答by widged
What I do is give each one of my reusable component a unique custom element name and then create a css file for that component, specifically, with all styling options for that component (and only for that component).
我所做的是为我的每个可重用组件指定一个唯一的自定义元素名称,然后为该组件创建一个 css 文件,特别是包含该组件的所有样式选项(并且仅适用于该组件)。
var MyDiv = React.createClass({
render: function() {
return <custom-component style={style}> Have a good and productive day! </custom-component>;
}
});
And in file 'custom-component.css', every entry will start with the custom-component tag:
在文件“custom-component.css”中,每个条目都以 custom-component 标签开头:
custom-component {
display: block; /* have it work as a div */
color: 'white';
fontSize: 200;
}
custom-component h1 {
font-size: 1.4em;
}
That means you don't loose the critical notion of separating of concern. View vs style. If you share your component, it is easier for other to theme it to match the rest of their web page.
这意味着您不会失去关注点分离的关键概念。视图与样式。如果您共享您的组件,其他人更容易将其主题化以匹配他们网页的其余部分。
回答by Anupam Maurya
Here is the boolean based styling in JSXsyntax:
这是JSX语法中基于布尔值的样式:
style={{display: this.state.isShowing ? "inherit" : "none"}}
回答by Alireza
It's really depends on how bigyour application is, if you wanna use bundlers like webpackand bundle CSS and JS together in the build and how you wanna mange your application flow! At the end of day, depends on your situation, you can make decision!
这真的取决于如何大你的应用程序是,如果你想用捆扎机喜欢的WebPack在构建和捆绑CSS和JS在一起,你想如何管理您的应用程序流!在一天结束时,取决于您的情况,您可以做出决定!
My preference for organising files in big projects are separating CSS and JSfiles, it could be easier to share, easier for UI people to just go through CSS files, also much neater file organising for the whole application!
我在大项目中组织文件的偏好是将CSS 和 JS文件分开,这样可以更容易共享,UI 人员更容易浏览 CSS 文件,并且整个应用程序的文件组织也更整洁!
Always think this way, make sure in developing phase everything are where they should be, named properly and be easy for other developers to find things...
总是这样想,确保在开发阶段一切都在它们应该在的地方,正确命名并且其他开发人员很容易找到东西......
I personally mix them depends on my need, for example... Try to use external css, but if needed React will accept style as well, you need to pass it as an object with key value, something like this below:
我个人根据我的需要混合它们,例如...尝试使用外部 css,但如果需要,React 也会接受样式,您需要将其作为具有键值的对象传递,如下所示:
import React from 'react';
const App = props => {
return (
<div className="app" style={{background: 'red', color: 'white'}}> /*<<<<look at style here*/
Hello World...
</div>
)
}
export default App;
回答by VocoJax
For some components, it is easier to use inline styles. Also, I find it easier and more concise (as I'm using Javascript and not CSS) to animate component styles.
对于某些组件,使用内联样式更容易。此外,我发现为组件样式设置动画更容易和更简洁(因为我使用的是 Javascript 而不是 CSS)。
For stand-alone components, I use the 'Spread Operator' or the '...'. For me, it's clear, beautiful, and works in a tight space. Here is a little loading animation I made to show it's benefits:
对于独立组件,我使用“Spread Operator”或“...”。对我来说,它清晰、美观,而且可以在狭小的空间内工作。这是我制作的一个加载动画来展示它的好处:
<div style={{...this.styles.container, ...this.state.opacity}}>
<div style={{...this.state.colors[0], ...this.styles.block}}/>
<div style={{...this.state.colors[1], ...this.styles.block}}/>
<div style={{...this.state.colors[2], ...this.styles.block}}/>
<div style={{...this.state.colors[7], ...this.styles.block}}/>
<div style={{...this.styles.block}}/>
<div style={{...this.state.colors[3], ...this.styles.block}}/>
<div style={{...this.state.colors[6], ...this.styles.block}}/>
<div style={{...this.state.colors[5], ...this.styles.block}}/>
<div style={{...this.state.colors[4], ...this.styles.block}}/>
</div>
this.styles = {
container: {
'display': 'flex',
'flexDirection': 'row',
'justifyContent': 'center',
'alignItems': 'center',
'flexWrap': 'wrap',
'width': 21,
'height': 21,
'borderRadius': '50%'
},
block: {
'width': 7,
'height': 7,
'borderRadius': '50%',
}
}
this.state = {
colors: [
{ backgroundColor: 'red'},
{ backgroundColor: 'blue'},
{ backgroundColor: 'yellow'},
{ backgroundColor: 'green'},
{ backgroundColor: 'white'},
{ backgroundColor: 'white'},
{ backgroundColor: 'white'},
{ backgroundColor: 'white'},
{ backgroundColor: 'white'},
],
opacity: {
'opacity': 0
}
}
EDIT NOVEMBER 2019
2019 年 11 月编辑
Working in the industry (A Fortune 500 company), I am NOT allowed to make any inline styling. In our team, we've decided that inline style are unreadable and not maintainable. And, after having seen first hand how inline styles make supporting an application completely intolerable, I'd have to agree. I completely discourage inline styles.
在这个行业工作(财富 500 强公司),我不允许做任何内联样式。在我们的团队中,我们认为内联样式不可读且不可维护。而且,在亲眼目睹内联样式如何使支持应用程序完全无法忍受之后,我不得不同意。我完全不鼓励内联样式。