我知道你可以在React类中指定样式,像这样:

const MyDiv = React.createClass({
  render: function() {
    const style = {
      color: 'white',
      fontSize: 200
    };
    
    return <div style={style}> Have a good and productive day! </div>;
  }
});

我应该瞄准这样做的所有样式,并没有在我的CSS文件中指定的样式吗?

或者我应该完全避免内联样式?

这似乎有点奇怪和混乱做一点两者-两个地方需要检查时调整样式。


当前回答

style属性的主要用途是动态的、基于状态的样式。例如,您可以在进度条上基于某种状态设置宽度样式,或者基于其他内容设置位置或可见性。

JS中的样式限制了应用程序不能为可重用组件提供自定义样式。在前面提到的情况下,这是完全可以接受的,但当您更改可见特征时,尤其是颜色。

其他回答

内联样式的问题是内容安全策略(CSP)越来越普遍,不允许使用内联样式。因此,我建议完全避免使用内联样式。

更新: 为了进一步解释,CSP是服务器发送的HTTP报头,用于限制页面上可以出现的内容。这只是进一步的缓解措施,可以应用到服务器上,以阻止攻击者在开发人员对站点编写糟糕的代码时做一些调皮的事情。

The purpose of most of these restrictions is to stop XSS (cross-site scripting) attacks. XSS is where an attacker figures out a way to include his own javascript on your page (for example, if I make my username bob<SCRIPT>alert("hello")</SCRIPT> and then post a comment, and you visit the page, it shouldn't show an alert). Developers should deny the ability to have a user add content like this to the site, but just in case they made a mistake, then CSP blocks the page from loading if it finds any script> tags.

CSP只是对开发人员的额外保护级别,以确保如果他们犯了错误,攻击者不会对该站点的访问者造成问题。

所以这一切都是XSS,但如果攻击者不能包括<script>标签,但可以包括<style>标签或在标签上包含style=参数呢?然后,他可能会改变网站的外观,使您被骗点击错误的按钮,或者出现其他问题。这不是什么大问题,但仍然需要避免,CSP可以为您做到这一点。

用于测试CSP站点的一个很好的资源是https://securityheaders.io/

你可以在http://www.html5rocks.com/en/tutorials/security/content-security-policy/上阅读更多关于CSP的信息

我所做的是为每个可重用组件提供一个唯一的自定义元素名称,然后为该组件创建一个CSS文件,特别是包含该组件的所有样式选项(并且仅针对该组件)。

var MyDiv = React.createClass({
  render: function() {
    return <custom-component style={style}> Have a good and productive day! </custom-component>;
  }
});

在文件'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; 
}

这意味着你不会失去关注点分离的关键概念。视图与样式。如果你共享你的组件,其他人更容易将其主题化以匹配他们网页的其余部分。

2020年更新:最好的做法是使用一个已经为你完成了艰苦工作的库,并且在你进行转换时不会杀死你的团队,正如本视频中最初接受的答案所指出的那样(它仍然相关)。为了了解趋势,这是一个非常有用的图表。在做了自己的研究之后,我选择在我的新项目中使用Emotion,它被证明是非常灵活和可扩展的。

鉴于2015年投票最多的答案是推荐镭,现在已经进入维护模式。因此,增加一些备选方案似乎是合理的。停止使用镭的帖子建议使用几个图书馆。每个链接的网站都有现成的示例,所以我将避免在这里复制和粘贴代码。

Emotion which is "inspired by" styled-components among others, uses styles in js and can be framework agnostic, but definitely promotes its React library. Emotion has been kept up to date as of this post. styled-components is comparable and offers many of the same features as Emotion. Also actively being maintained. Both Emotion and styled-components have similar syntax. It is built specifically to work with React components. JSS Yet another option for styles in js which is framework agnostic though it does have a number of framework packages, React-JSS among them.

对于某些组件,使用内联样式更容易。此外,我发现它更容易和更简洁(因为我使用Javascript而不是CSS)动画组件样式。

对于独立组件,我使用“扩展操作符”或“…”。对我来说,它清晰、美丽,在狭小的空间里也能工作。下面是我制作的一个加载动画来展示它的好处:

<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
  }
}

2019年11月

在这个行业(一家财富500强公司)工作,我不允许做任何内联样式。在我们的团队中,我们认为内联样式是不可读和不可维护的。而且,在亲眼看到内联样式如何使支持应用程序变得完全无法忍受之后,我不得不同意这一点。我完全反对内联样式。

我更喜欢使用样式化组件。为设计提供了较好的解决方案。

import React, { Component, Fragment } from 'react'
import styled from 'styled-components';

const StyledDiv = styled.div`
    display: block;
    margin-left: auto;
    margin-right: auto;
    font-size:200; // here we can set static
    color: ${props => props.color} // set dynamic color by props
`;

export default class RenderHtml extends Component {
    render() {
        return (
            <Fragment>
                <StyledDiv color={'white'}>
                    Have a good and productive day!
                </StyledDiv>
            </Fragment>
        )
    }
}