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

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

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


当前回答

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

HTML的例子:

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

JSX案例:

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

其他回答

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.

你可以使用内联样式,但你会有一些限制,如果你在所有的样式中使用它们,一些已知的限制是你不能在那里使用CSS伪选择器和媒体查询。

你可以用镭来解决这个问题,但我觉得随着项目的发展,它会变得很麻烦。

我建议使用CSS模块。

使用CSS模块,你将有在CSS文件中写CSS的自由,不必担心命名冲突,这将由CSS模块照顾。

这种方法的一个优点是,它为特定组件提供了样式化功能。这将为下一个开发人员创建更易于维护的代码和可读的项目架构。

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

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

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

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