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

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

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


当前回答

无论如何,内联css是不推荐的。我们在基于JSS的项目中使用了样式组件。它通过在组件上添加动态类名来保护css覆盖。您还可以根据传递的道具添加css值。

其他回答

根据您的配置,内联样式可以为您提供热重载。每次样式改变时,网页都会立即重新呈现。这有助于我更快地开发组件。话虽如此,我相信你可以为CSS + SCSS设置一个热重载环境。

JSX中的样式与HTML中的样式非常相似。

HTML的例子:

Div style="background-color: red;颜色:白色”

JSX案例:

div style={{backgroundColor: '红色',color: '白色'}}

有时候,我们需要从组件中样式化一些元素,但如果我们必须只显示该组件的一个元素,或者样式是如此之少,那么我们不使用CSS类,而是在react js中使用内联样式。reactjs的内联样式和HTML的内联样式是一样的,只是属性名略有不同

使用style={{prop:"value"}}在任何标签中写入样式

import React, { Component } from "react";
    import { Redirect } from "react-router";

    class InlineStyle extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }

      render() {
        return (
          <div>
            <div>
              <div
                style={{
                  color: "red",
                  fontSize: 40,
                  background: "green"
                }}// this is inline style in reactjs
              >

              </div>
            </div>
          </div>
        );
      }
    }
    export default InlineStyle;

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

React中的style属性期望值是一个对象,即键值对。

Style ={}将在其中包含另一个对象,如{float:'right'},以使其工作。

<span style={{float:'right'}}>Download Audit</span>

希望这能解决问题