我知道你可以在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>;
  }
}

其他回答

我通常有与每个React组件相关联的scss文件。但是,我不明白为什么你不封装组件与逻辑,并查看它。我的意思是,你有类似的web组件。

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

HTML的例子:

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

JSX案例:

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

James K Nelson在他的信“为什么你不应该用JavaScript样式化React组件”中指出,实际上没有必要使用内联样式及其缺点。他的观点是,旧的无趣的CSS加上较少的/scss是最好的解决方案。他的论文中支持CSS的部分:

可扩展的外部 可分割(内联样式超越一切) define_image_transformation

你也可以使用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>;
  }
}

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.