我知道你可以在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文件中指定的样式吗?

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

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


当前回答

你也可以使用StrCSS,它可以创建独立的类名等等!示例代码如下所示。你可以(可选)从Visual Studio市场安装VSCode扩展来支持语法高亮显示!

来源:strcss

import { Sheet } from "strcss";
import React, { Component } from "react";

const sheet = new Sheet(`
  map button
    color green
    color red !ios
    fontSize 16
  on hover
    opacity .5
  at mobile
    fontSize 10
`);

export class User extends Component {
  render() {
    return <div className={sheet.map.button}>
      {"Look mom, I'm green!
      Unless you're on iOS..."}
    </div>;
  }
}

其他回答

下面是JSX语法中基于布尔的样式:

style={{display: this.state.isShowing ? "inherit" : "none"}}

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

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

我在React组件中广泛使用内联样式。我发现在组件中搭配样式非常清楚,因为组件有什么样式,没有什么样式总是很清楚的。此外,拥有Javascript的全部功能确实简化了更复杂的样式需求。

一开始我并不相信,但在尝试了几个月后,我完全转换了,并且正在将我所有的CSS转换为内联或其他js驱动的CSS方法。

Facebook员工和React贡献者“vjeux”的演示也很有帮助- https://speakerdeck.com/vjeux/react-css-in-js

你也可以使用StrCSS,它可以创建独立的类名等等!示例代码如下所示。你可以(可选)从Visual Studio市场安装VSCode扩展来支持语法高亮显示!

来源:strcss

import { Sheet } from "strcss";
import React, { Component } from "react";

const sheet = new Sheet(`
  map button
    color green
    color red !ios
    fontSize 16
  on hover
    opacity .5
  at mobile
    fontSize 10
`);

export class User extends Component {
  render() {
    return <div className={sheet.map.button}>
      {"Look mom, I'm green!
      Unless you're on iOS..."}
    </div>;
  }
}

内联样式的问题是内容安全策略(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的信息